0

我有这样的功能:

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 
    });
}

我的问题是callbackinside.done()不是在每个async callinside之后执行的a()

我该如何解决?我如何才能在执行callbacka()执行?

注意firstAsyncCall secondAsyncCallcallback里面.done()都是asynchronous东西

4

2 回答 2

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/

于 2013-07-16T14:20:08.723 回答
1

这完全取决于您要达到的目标,但让我们假设:

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

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

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()

于 2013-07-16T22:46:58.593 回答