简体   繁体   中英

Fire ajax call after all the previous ajax calls have completed

Lets say I have functions like:

function A(){
    func B();
    ajax call last;
}

func B(){
   if some condition1
       func C();
   if some condition2
       func D();
   if some condition3
       func E();
}

func C(){
     some ajax cal 1
}

func D(){
     ajax call 2
}

func E(){
     ajax call 3
}

My problem is ajax call last should be fired only when all the previous ajax calls have completed .ie ajax call 1 , 2 , 3.

If you're using jQuery then you have access to various calls based on a promise . Calls to $.ajax return a promise that can be used to defer subsequent calls. See the documentation for the jQuery when call (docs here ).

Using when you can execute a function after a $.ajax call has completed. You can use the same technique for a single such call to $.ajax , or multiple calls.

I'm not sure based on your question how you want to chain the calls, but here's an attempt based on your code (untested but this should get you on the right track):

func B()
{
    var callC = null;
    var callD = null;
    var callE = null;

    if (condition1)
        callC = $.ajax("/call/1");

    if (condition2)
        callD =  $.ajax("/call/2");

    if (condition3)
        callE =  $.ajax("/call/3");

    $.when(callC, callD, callE).then($.ajax("/call/last"));
}

.then will execute once the 3 AJAX calls have completed , regardless of their success or failure. Also look at .done if you only want to continue if all calls return success.

Try utilizing return , .then()

function A() {
    return B();
}

function B() {
   if (some_condition1) {
       return C();
   };
   if (some_condition2) {
       return D();
   };
   if (some_condition3) {
       return E();
   };
}

function C() {
     // some ajax call 1
     return $.ajax()
}

function D() {
     // ajax call 2
     return $.ajax()
}

function E() {
     // ajax call 3
     return $.ajax()
}

A().then(function() {
  // ajax call last;
  return $.ajax()
});

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