gpt4 book ai didi

javascript - 使用异步 Ajax 获取数据的 Memoizing Javascript 函数

转载 作者:行者123 更新时间:2023-11-29 18:09:58 25 4
gpt4 key购买 nike

假设我有获取模板的功能,如果模板以前从未使用过,它应该通过 AJAX 发送请求,然后返回模板,如果使用了模板,它应该从缓存中返回。

示例代码:

var getTemplate = (function(jQuery){
//full template obj = {url: '', html: ''}
var templates = {test: {url: '/templates/test.html'}};

function getTemplate(templateId){
if(templates[templateId].html){
return templates[templateId];
}

jQuery.ajax({
method: "get",
url: templates[templateId].url
}).success(function(respond){
templates[templateId].html = respond;
});

//no idea what next...

return getTemplate
}
})(jQuery);

示例使用:

var template = getTemplate('test') 应该总是返回 /templates/test.html 内容

我不会使用 async: false 和任何框架。我不会学习如何做到这一点;)

最佳答案

由于您希望缓存模板并在已经可用的情况下立即解析它们,因此您需要确保 API 在这两种情况下都是一致的。这意味着您的函数应该实现某种延迟或 promise 接口(interface)。例如:

var getTemplate = (function(jQuery) {

var templates = {
test: {
url: 'templates/test.html'
}
};

return function(templateId) {

if (templates[templateId].html) {
return jQuery.when(templates[templateId].html);
}

return jQuery.ajax({
url: templates[templateId].url
})
.then(function(responce) {
templates[templateId].html = responce;
return responce;
});
}
})(jQuery);

那么用法是:

getTemplate('test').done(function(html) {
console.log(html);
});

演示:http://plnkr.co/edit/jutnHSQDAA4HLnmS0DqR?p=preview

关于javascript - 使用异步 Ajax 获取数据的 Memoizing Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28293405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com