1

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?

0

2 Answers 2

3

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, I figured I could also have a counter that increases with each .done() callback and then check if the counter equals the amount of ajax calls and then do something, but I'm using your solution as it seems more elegant...
Indeed, this way is better than mine since it allows for error handling. Promises are also a neat feature. I'll point out that the array should properly be a constant (as it is already) lest it be reassigned before the promises complete. This is a concise and thorough answer.
1

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

1 Comment

I ended up using the other answer but this works too, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.