我有一个三层深度的延迟ajax调用链,理想情况下,它们会在最深层完成时将承诺一直向上踢(这让我有点像Inception……“我们需要更深入!”)。
问题是我一次发送了许多ajax请求(可能有数百个),并且需要推迟到所有请求都完成之后。我不能相信最后一个是最后完成的。
function updateAllNotes() {
return $.Deferred(function(dfd_uan) {
getcount = 0;
getreturn = 0;
for (i = 0; i <= index.data.length - 1; i++) {
getcount++;
$.when(getNote(index.data[i].key)).done(function() {
// getNote is another deferred
getreturn++
});
};
// need help here
// when getreturn == getcount, dfd_uan.resolve()
}).promise();
};发布于 2011-07-03 00:50:12
您可以使用.when()和.apply()来实现多个延迟。非常有用:
function updateAllNotes() {
var getarray = [],
i, len;
for (i = 0, len = data.length; i < len; i += 1) {
getarray.push(getNote(data[i].key));
};
$.when.apply($, getarray).done(function() {
// do things that need to wait until ALL gets are done
});
}发布于 2012-11-29 22:08:06
如果参考jQuery.When文档,如果其中一个ajax调用失败,fail主回调将被调用,即使后面所有ajax调用还没有完成。在这种情况下,您不能确定所有呼叫都已完成。
如果你想等待所有的呼叫,不管结果是什么,你必须使用另一个像这样的延迟:
$.when.apply($, $.map(data, function(i) {
var dfd = $.Deferred();
// you can add .done and .fail if you want to keep track of each results individualy
getNote(i.key).always(function() { dfd.resolve(); });
return dfd.promise();
});发布于 2012-08-07 06:10:02
谢谢你给我的答案。我还使用了下划线,所以我可以非常清晰地将您的解决方案应用到map中,有点像这样:
$.when.apply($, _.map(data, function(i) {
return getNote(i.key);
})).done(function() {
alert('Be Happy');
});非常有用。
https://stackoverflow.com/questions/6538470
复制相似问题