仅在上一次异步调用后执行ajax

时间:2013-07-16 10:37:05

标签: jquery ajax asynchronous deferred

我有这样的功能:

var a = function(){
    var that = this;
    var datas = ["data1", "data2",.., "dataN"];
    var dfd = new $.Deferred();
    $.each(datas, function(i,el){
       firstAsyncCall(el); //it does asynchrounus stuff
    });
    secondAsyncCall();
    dfd.resolve();
    return dfd.promise();
    } 

然后

var b = function() {
    a.done( function() { 
    //other async stuff 
    });
}

我的问题是callback内的.done() async calla()callbacka()内没有firstAsyncCall

我该如何解决?如何在执行secondAsyncCall之后执行callback

请注意.done()内的asynchronous {{1}}和{{1}}都是{{1}}内容

2 个答案:

答案 0 :(得分:1)

我第一次尝试这样可能是错的,或者可能不是你想要的结果,希望它有所帮助:

function firstAsyncCall(el){
    return $.get( "/echo/json/" ).done(function(){
        $("#"+el).css("background", "red");
    });
}

function secondAsyncCall(){
    return $.get( "/echo/json/" ).done(function(){
        $("div").css("border", "2px solid blue");
    });
}

var a = function(){
    var that = this;
    var ajaxReq = [];
    var datas = ["data1", "data2", "data3"];
    var dfd = new $.Deferred();

    $.each(datas, function(i,el){
       ajaxReq.push(firstAsyncCall(el));
    });
    ajaxReq.push(secondAsyncCall());
    $.when.apply($, ajaxReq).then(function(){
        dfd.resolve();
    });   
    return dfd.promise()
}

var b = function() {
    var myA = a();
    myA.done( function() { 
        $("div").css("background", "green");
    });
}
b();

http://jsfiddle.net/Fq99A/

答案 1 :(得分:1)

这取决于你想要达到的目标,但我们假设:

  • secondAsyncCall()将在所有 firstAsyncCall()来电成功完成后执行
  • secondAsyncCall()成功完成后,应发生“其他异步内容”。

首先,确保firstAsyncCall()secondAsyncCall()各自返回一个承诺。

var a = function() {
    var datas = ["data1", "data2",.., "dataN"];
    var firstPromises = $.map(datas, function(el, i) {
        return firstAsyncCall(el); //it does asynchrounus stuff
    });

    //At this point, firstPromises is an array of promises.

    return $.when.apply(null, firstPromises).then(secondAsyncCall);
};

您现在可以写:

var b = function() {
    return a().then(function() {
        //other async stuff 
    });
};

通过返回a().then(...)生成的承诺,您可以使用b().then(...)b().done(...)b().fail()b().always()链接更多操作。