bri*_*ran 56 jquery jquery-deferred
我有一个三层深度的延迟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();
};
Run Code Online (Sandbox Code Playgroud)
bri*_*ran 107
您可以使用.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
});
}
Run Code Online (Sandbox Code Playgroud)
Mor*_*hak 27
如果您引用jQuery.Whendoc,如果您的某个ajax调用失败,fail即使所有后续的ajax调用尚未完成,也会调用主回调.在这种情况下,您不确定所有通话都已完成.
如果你想等待所有的通话,无论结果是什么,你必须使用另一个Deferred,如下所示:
$.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();
});
Run Code Online (Sandbox Code Playgroud)
谢谢你回答brittohalloran.我也在使用Underscore,所以我能够非常干净地使用地图来应用你的解决方案,有点像这样:
$.when.apply($, _.map(data, function(i) {
return getNote(i.key);
})).done(function() {
alert('Be Happy');
});
Run Code Online (Sandbox Code Playgroud)
邪恶有用.
| 归档时间: |
|
| 查看次数: |
47791 次 |
| 最近记录: |