GibboK
GibboK

Reputation: 73938

Working with several asynchronous requests

Suppose my app needs to do several asynchronous requests, but I want to work with the data only once all requests are complete.

What is the simplest way to achieve this in vanilla JS or jquery? Sample of code appreciate thanks

Upvotes: 1

Views: 52

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318548

jQuery's promise system allows you to do this easily:

$.when(req1, req2, req3).done(function(res1, res2, res3) {
    // all requests finished successfully
});

The reqN variables need to be promise objects, such as the ones returned by $.ajax().

If you have an array of them instead of separate variables, you can use this instead:

$.when.apply($, reqs).done(...);

Related documentation: http://api.jquery.com/jQuery.when/

Upvotes: 5

Related Questions