NycCompSci
NycCompSci

Reputation: 3137

Algorithm for setting a handler for when multiple ajax request returns in JS

I am writing a program where I need to put out n number of Ajax requests, I want to write a handler to be executed when all of them returns.

What is a good way to do this?

*my initial thought is to create a counter that is incremented when you create a request and decremented when the request returns. When you are at 0, do your handler. However, this creates a race condition where if you don't create your requests fast enough, your previous requests might return first and decrement your counter to 0 and execute the handler. Is there a better way to do this?

Upvotes: 1

Views: 99

Answers (1)

SLaks
SLaks

Reputation: 887797

Your initial thought is actually perfectly fine.

Since Javascript is single-threaded, you won't get any callbacks while your code is running.
As long as you create all of the requests in the same event handler, you're fine.

If you don't create all the requests at once, you'll either need to know in advance how many requests you're going to create, or handle partial responses.

Upvotes: 1

Related Questions