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