如何推迟多个ajax成功回调?

时间:2013-05-14 20:18:35

标签: javascript ajax callback synchronization

在我的Javascript中,我有以下场景:

call_A(success_A)

call_B(success_B)


function call_A(success){
// make ajax request
success(result)
}

function call_B(success){
//make ajax request
success(result)
}


function success_A(){
  //set data to be used by success_B
}

function success_B(){
..do some stuff
}

我希望一个接一个地call_Acall_B,以便进行ajax调用(以节省时间)。

我没有更改call_Acall_B函数头的选项,因此必须调用这些函数来指定成功回调函数。

我想要的是,无论2 ajax调用中的哪一个首先完成,我都希望在success_A之前调用success_B,因为B依赖于A的数据。

完成这项工作的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

a_success= false;
b_success= false;

call_A(generalSuccess);
call_B(generalSuccess);

function call_A(success) {
    // make ajax request
    a_success = true;
    success(result)
}

function call_B(success) {
    //make ajax request
    b_success = true;
    success(result)
}

function generalSuccess() {
    //assuming you are passing which a or b is called. set b_success or a_success is true
    if (a_success == true && b_success == true) {
        // use all variables you need and get the final result
    } else if (a_success == true) {
        // set your desired value into a global variable from a request
    } else if (b_success == true) {
        // set results to use from b request.
    }
}