我读到了最上面的答案这个问题 https://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used关于使用jQuery 延迟 http://api.jquery.com/category/deferred-object/.
我正在循环遍历 ID 数组。对于每个 ID,我需要从 ajax 请求获取与其相关的数据,或者如果 ajax 请求之前已成功返回数据,则需要从缓存获取数据。
在每个循环中,我在处理该 ID 之前使用 $.when() 来观察 getData() 是否从缓存返回某些内容或成功的 ajax 调用。当前的问题是 ID 处理无论如何都会继续进行,而无需等待 getData() 的 ajax 成功。
一些伪代码:
var IDs = ["1", "2", "1", "3", "1"];
//ID "1" is repeated
//data for "1" should should require ajax get the first time
//subsequent processing should get data for "1" from dataCache
var dataCache = [];
function getData(ID){
if (/*data for ID in dataCache*/){
//return data pertaining to ID from dataCache
} else {
return $.getJSON("returnJSONDataByID/" + ID, function(resp){
//push resp data to dataCache
})
}
}
for (/*each item i in IDs*/){
$.when(getData(IDs[i])).then(function(){
//process IDs[i] data
//this is the resolved handler, which should be executed
//when either getData() returns data from the dataCache,
//or $.getJSON succeeds
//PROBLEM: this is currently executing every loop and
//and doesn't wait for the ajax to return resp
})
}
问题是你的循环将触发所有getData
立即调用,但结果仅在 JSON 调用返回后存储在缓存中。因此,对于循环中的每个调用,缓存仍然为空,并且每个调用都将执行新的 JSON 请求。
解决方案:代替结果存储Deferred
缓存中的对象。
var IDs = ["1", "2", "1", "3", "1"];
var dataCache = {};
function getData(id) {
if (id in dataCache) {
console.log("Cache hit for ID " + id);
return dataCache[id];
} else {
console.log("Retrieving data for ID " + id);
var deferred = $.getJSON("http://jsfiddle.net/echo/jsonp/?callback=?", {
id: id
}, function(response) {
console.log("Retrieved data for ID " + id);
});
dataCache[id] = deferred;
return deferred;
}
}
for (var i=0; i<IDs.length; i++) {
$.when(getData(IDs[i])).then(function(result) {
console.log("result: " + result.id);
});
}
注意:这是工作代码,您可以在 jsFiddle 中玩它 http://jsfiddle.net/green/XKArL/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)