JavaScript: ordering AJAX calls

I have 3 ajax calls for specific functionality. The third call depends on the first two calls, i.e. For the 3rd call, 2 calls must first be made. But the first two AJAX calls are independent. Therefore, I want them to be asynchronous and run in parallel.

How to structure these challenges now? I tried to put them in the nested success block of the corresponding calls, but in this case the first two calls are also not independent.

Please suggest using some sudo code if possible.

+6
source share
2 answers

Use promises and $.when :

 $.when(ajaxCall1(), ajaxCall2()).then(ajaxCall3); 

where ajaxCallX is something like

 function ajaxCall1() { return $.ajax(...); } 

This basically means "after both, the promise of ajaxCall1 and the promise of ajaxCall2 allowed, execute the function ajaxCall3 ."

This works because the object returned by $.ajax (and similar methods) implements the promise interface. See the $.ajax documentation for more details.


The responses of each Ajax call are passed in response to then as arguments. You can use them as

 $.when(ajaxCall1(), ajaxCall2()).then(function(a1, a2) { // a1[0] is the response of the first call // a2[0] is the response of the second call ajaxCall3(a1[0], a2[0]); }); 

Take a look at the $.when documentation for another example.

+14
source

You can use ajaxComplete to call the third event after the completion of the first two events. ajaxComplete is a callback event that fires after each ajaxCalls response. Check out this link to find how it works https://api.jquery.com/ajaxComplete/

+1
source

All Articles