如何确定多个 ajax 回调何时完成
How to determine when multiple ajax callbacks have completed
已经提出了几个具有这种确切性质的问题。其中一个没有得到答复,其中一个准确地提出了我正在尝试的方法,但没有成功。
这是我想要做的事情:
函数 a() 将被调用 1 到多次。
函数 b() 执行异步调用。
for (i=0; i<=something; i++) {
function a() {
function b(); //makes async call
}
}
// at this point, execution continues,
// even though all function b()'s async
// calls are still "pending".
由于函数 b() 中的异步调用,函数 a() 本身也是异步的。
我需要一些方法来了解函数 b() 的所有异步调用何时完成。
我试过这个:
var callCount=0;
for (i=0; i<=something; i++) {
function a() {
callCount++;
function b(callCount);
}
}
然后我让函数 b() 的异步回调函数递减 callCount,然后这样做:
var callCount=0;
for (i=0; i<=something; i++) {
function a() {
callCount++;
function b(callCount); // b()'s callback decrements callCount by 1;
}
}
while (callCount > 0) {
}
// now continue
但是在 for() 循环结束时,callCount 仍然包含调用次数,并且永远不会递减,从而导致无限循环。
callCount 在 b() 的回调函数中是不可变的吗?
是否有任何方法可以检测多个异步调用何时全部完成?我同时使用 jquery .ajax() 和 .get()。
在 promises 和 deferred introduction 之后...你只需要保留一系列 promises 并使用 $.when 和 apply
$.when.apply($, promises).then(function() {
console.log('All ajax calls completed');
});
请查看此 working fiddle,只需打开您的控制台即可。
已经提出了几个具有这种确切性质的问题。其中一个没有得到答复,其中一个准确地提出了我正在尝试的方法,但没有成功。
这是我想要做的事情:
函数 a() 将被调用 1 到多次。 函数 b() 执行异步调用。
for (i=0; i<=something; i++) {
function a() {
function b(); //makes async call
}
}
// at this point, execution continues,
// even though all function b()'s async
// calls are still "pending".
由于函数 b() 中的异步调用,函数 a() 本身也是异步的。
我需要一些方法来了解函数 b() 的所有异步调用何时完成。
我试过这个:
var callCount=0;
for (i=0; i<=something; i++) {
function a() {
callCount++;
function b(callCount);
}
}
然后我让函数 b() 的异步回调函数递减 callCount,然后这样做:
var callCount=0;
for (i=0; i<=something; i++) {
function a() {
callCount++;
function b(callCount); // b()'s callback decrements callCount by 1;
}
}
while (callCount > 0) {
}
// now continue
但是在 for() 循环结束时,callCount 仍然包含调用次数,并且永远不会递减,从而导致无限循环。
callCount 在 b() 的回调函数中是不可变的吗?
是否有任何方法可以检测多个异步调用何时全部完成?我同时使用 jquery .ajax() 和 .get()。
在 promises 和 deferred introduction 之后...你只需要保留一系列 promises 并使用 $.when 和 apply
$.when.apply($, promises).then(function() {
console.log('All ajax calls completed');
});
请查看此 working fiddle,只需打开您的控制台即可。