Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Ordering AJAX calls

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.

like image 911
Dhruv Bansal Avatar asked Feb 16 '14 04:02

Dhruv Bansal


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 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.

like image 98
Felix Kling Avatar answered Sep 27 '22 00:09

Felix Kling


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/

like image 24
Karthik Surianarayanan Avatar answered Sep 27 '22 00:09

Karthik Surianarayanan