I have 3 ajax call for particular functionality. 3rd call is dependent of first 2 calls i.e. for the 3 rd call first 2 calls has to be finished. But first 2 AJAX calls are independent. So I want them to be async and execute parallely.
How to structure these calls now? I tried to put them in nested success block of respective calls, but it that case first 2 calls are also not independent.
Kindly suggest with some sudo code, if possible.
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
are resolved, execute the function ajaxCall3
".
This works because the object returned by $.ajax
(and similar methods) implements the promise interface. More information can also be found in the $.ajax
documentation.
The responses of each Ajax call are passed to the then
callback as arguments. You can acess 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]);
});
Have a look at the $.when
documentation for another example.
You can make use of ajaxComplete to call the third event after the first two events completes execution. ajaxComplete is an callback event which is fired after each and every ajaxCalls got response. Look over this link to find how it works https://api.jquery.com/ajaxComplete/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With