Run Multiple AJAX in Parallel using JQuery

I want to execute/run multiple ajax in parallel request or simultaneously. Instead of waiting for the first ajax request to complete and then issue the second request is time-consuming. 

To resolving this issue i found a solution which i am describing here. So buckle up and stay with us.

I personally recommend you to know about Promise and a Callback function concept in JQuery to understand this concept more easily.

To run multiple AJAX in parallel, we'll use jQuery .when(). The $.when() provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

The basic syntax is:

$.when(request1, request2, request3.....) 

Lets move on to the implementation

I am going to use Flickr API to get the images. The first request will fetch photos which are tagged with "moon" and the second request will fetch photos tagged with "bird". And then we display the results in a div of both the requests.

So here is 2 ajax request to flickr API. To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the ajax request are finished. 

In the case where multiple Deferred objects are passed to $.when(), it takes the response returned by both calls, and constructs a new promise object. The res1 and res2 arguments of the callback are arrays, where res1 has response of first request and res2 has response from second request.

Want to read about Promises: A complete explanation of modern JavaScript

Source code: Run multiple AJAX in Parallel
Source code: Run multiple AJAX in Parallel

You can also declare what to do in case of success and failure of ajax request.

See demo here:http://jsfiddle.net/dasjs/ftnky361/

Below jQuery code execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.

$.when(
   $.ajax("/page1.php"), 
   $.ajax("/page2.php")
  ).then(myFunc, myFailure);

Read more about $.when.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Leave a Reply

Your email address will not be published. Required fields are marked *