简体   繁体   中英

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?

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. Once all calls resolve, the Promise.all will resolve to an array of the four responses:

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. When the counter equals 4, you can do something with the results array.

(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
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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