我需要在递归异步ajax调用后执行一个函数。 我有:
var tree = [1, 2 ,3, 4];
recursion(0);
function recursion(i) {
$.ajax('http://example.com/' + tree[i])
.done(function (data) {
// data is array
++i;
if (tree[i] !==undefined) {
$.each(data, function () {
recursion(i);
});
}
});
}
我希望在所有通话完成后执行以下操作:
recursion(0).done(function () {alert('All calls are done!')});
我知道,我应该使用JQuery的$.Deferred,但是ajax调用也返回promise。 我正在尝试使用 $.Deferred 但我在这个地方遇到了循环问题:
$.each(data, function () {
recursion(i);
});
请帮助我。
最佳答案
I'm trying to use $.Deferred
好!
but I encountered a problem with loop in this place:
$.each(data, recursion)
每个 recursion(i)
调用都会返回一个 Promise,因此当我们启动它们时,我们会留下一个 Promise 集合。现在,我们可以使用$.when
至 wait for all of them ,并获得所有结果的 promise 。
现在,我们使用then
在 ajax 调用之后链接此循环执行,以便我们可以返回此递归步骤的最终结果的 promise 。
function recursion(i, x) {
return $.ajax('http://example.com/' + tree[i] + x).then(function (data) {
if (++i < tree.length)
// get an array of promises and compose all of them
return $.when.apply($, $.map(data, function(d) {
return recursion(i, d);
}));
else // at the innermost level
return data; // get the actual results
}); // and return a promise for that
}
关于javascript - 在递归异步 ajax 调用后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551043/