5

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.

Dhruv
  • 10,291
  • 18
  • 77
  • 126
  • Similar to this question/answer: http://stackoverflow.com/questions/21792277/jquery-getting-rid-of-nested-ajax-functions/21792307#21792307 – jfriend00 Feb 16 '14 at 05:02
  • 1
    Read a very good article regarding parallel and series AJAX call http://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/ – Fizer Khan Feb 16 '14 at 05:58

2 Answers2

15

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • The OP probably needs the results from the first two ajax calls in order to feed into the third so perhaps you can explain how that might be accomplished when using this structure. – jfriend00 Feb 16 '14 at 05:00
1

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/