如何等待嵌套的异步jQuery AJAX请求完成?

我正在使用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. }); }); }); 

因此,当完成十个循环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. } ); } ); 

在第一个$ .when.apply()。then()的’done’函数中,第二批请求尚未完成,甚至已添加到promises_inner数组中。 但我发现添加嵌套的$ .when.apply()。then()似乎有效 – 在其“完成”函数中所有请求都已完成。

但我不确定这是最好,最强大的解决方案。 我担心这只会巧合 – 它会导致呼叫完成的延迟 – 而不是合乎逻辑。

有更好,更坚固的解决方案吗? 谢谢。

看一下1.7中的$ .Callbacks。 我认为你会对制作自己的“流程”的灵活性以及重用它们,运行一次等的能力感到兴奋。

你做了什么没有什么问题(应用模式可能不是大多数人的首选,他们通常只是将它们列在$ .when(a,b,c ….)中 – 但是你可能喜欢它的语法$ .Callbacks更好。

试试这个只有一个主要的承诺,每个循环运行fullfill(解决)(这里仍称为inner_promise)。

 var initial_data = [1,2,3,4,5,6,7,8,9,10]; var promises_inner = []; initial_data.forEach(function(n) { // Create promise for the inner call here. var promise_inner = $.Deferred(); promises_inner.push(promise_inner); $.ajax({url:'http://www.domain.com/etc/'+n}).done(function(data) { $.ajax({url:'http://www.domain.com/etc/'+data.result}).done(function(data) { // Do something with the content of data here. promise_inner.resolve(); }); }); }); console.log("promises_inner contains " + promises_inner.length + " promises") // should contain all the 10 promises $.when.apply($,promises_inner).done(function() { // The inner AJAX calls are finished now })