简体   繁体   中英

JavaScript : Ordering AJAX calls

I have 3 ajax call for particular functionality. 3rd call is dependent of first 2 calls ie 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM