Phi*_*ord 5 javascript ajax jquery
我正在使用jQuery,我有一个异步AJAX请求循环.我知道我可以使用方便的'$ .when.apply(array_of_requests).then()'方法等待它们全部完成.
但我还有另一组AJAX请求,只有在每个第一个请求完成后才会执行.我想等他们也完成,但我不是100%肯定我找到了最好的方法.
这是我的请求的简化示例:
var intital_data = [1,2,3,4,5,6,7,8,9,10];
var promises = [];
var promises_inner = [];
$.each(intitial_data, function(i, n) {
var ajax_call = $.ajax({url:'http://www.domain.com/etc/'+n});
promises.push(ajax_call);
ajax_call.done(function(data) {
var ajax_call_inner = $.ajax({url:'http://www.domain.com/etc/'+data.result});
promises_inner.push(ajax_call_inner);
ajax_call_inner.done(function(data) {
// Do something with the content of data here.
});
});
});
Run Code Online (Sandbox Code Playgroud)
因此,当完成十个循环AJAX请求中的每一个时,我根据第一个的结果发出第二个AJAX请求.一切正常.
然后我有这样的事情,因为我想要等到前十个请求(存储在promises数组中)和第二个批次(存储在promises_inner中)完成:
$.when.apply($, promises).then(
function() {
// The ten outer AJAX calls are finished now.
$.when.apply($, promises_inner).then(
function() {
// The inner AJAX calls are finished now.
}
);
}
);
Run Code Online (Sandbox Code Playgroud)
在第一个$ .when.apply().then()的'done'函数中,第二批请求尚未完成,甚至已添加到promises_inner数组中.但我发现添加一个嵌套的$ .when.apply().then()似乎可以工作 - 在其'done'函数中所有请求都已完成.
但我不确定这是最好,最强大的解决方案.我担心这只会巧合 - 它会导致呼叫完成的延迟 - 而不是合乎逻辑.
是否有更好,更坚固的解决方案?谢谢.
看一下 1.7 中的 $.Callbacks。我认为您会对创建自己的“流程”的灵活性以及重用它们、运行一次等的能力感到兴奋。
你所做的没有任何问题(应用模式可能不是大多数人的首选,他们通常只是将它们列在 $.when(a, b, c....) 中 - 但你可能喜欢以下语法$.回调更好。