简体   繁体   English

循环调用多个AJAX调用

[英]Callback of multiple AJAX calls in a loop

I have this code: 我有以下代码:

var results = [];

for(var i = 0; i < 4; i++){
   $.ajax(... results.push(response));
}

I want to know when those 4 ajax calls are done, and then do something with the results array, how can I do this? 我想知道这4个Ajax调用何时完成,然后对结果数组做些什么,我该怎么做?

Instead of creating a results array in advance, create an array of promises ( $.ajax calls count as promises), and then you can use Promise.all on the array. 无需预先创建results数组,而是创建一个promise数组( $.ajax调用计为promise),然后可以在该数组上使用Promise.all Once all calls resolve, the Promise.all will resolve to an array of the four responses: 一旦所有呼叫解决, Promise.all将解析为四个响应的数组:

const promises = [];
for (let i = 0; i < 4; i++) {
  promises.push($.ajax(....));
}
Promise.all(promises).then((results) => {
  // do stuff with results
})
.catch((err) => {
  // handle errors
});

You can introduce a counter that increments when each AJAX request returns. 您可以引入一个计数器,该计数器在每个AJAX请求返回时递增。 When the counter equals 4, you can do something with the results array. 当计数器等于4时,您可以对结果数组进行操作。

(I am responding with pseudo code as well, since I am typing this on my cell phone.) (我也在用伪代码进行响应,因为我是在手机上键入的。)

var counter = 0;
var results = [];
for (var i = 0; i < 4; i++) {
    $.ajax(..., function(resp) {
        counter++;
        results.push(resp);

        if (counter == 4) {
            // do stuff
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM