如何确定多个ajax回调何时完成

时间:2016-05-23 19:55:44

标签: javascript jquery ajax asynchronous

有几个问题已经被问过这个确切的性质。其中一个没有得到答案,其中一个建议我正在尝试,但没有成功。

这是我想要做的事情:

函数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()。

1 个答案:

答案 0 :(得分:1)

承诺和推迟介绍之后......你只需要保留一系列承诺并使用$ .when并申请

$.when.apply($, promises).then(function() {
  console.log('All ajax calls completed');
});

请点击此working fiddle,然后打开您的控制台。

相关问题