Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 仅在上一次异步调用后执行ajax_Jquery_Ajax_Asynchronous_Deferred - Fatal编程技术网

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

Jquery 仅在上一次异步调用后执行ajax,jquery,ajax,asynchronous,deferred,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()

我有这样一个函数:

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();
    } 
然后

我的问题是
内部
.done()
中的
回调在每次
异步调用后都不会执行
内部
a()

我怎样才能解决这个问题?如何仅在执行
a()
之后执行
回调


请注意,
firstAsyncCall
secondAsyncCall
callback
内部
.done()
都是
asynchronous
东西,我第一次尝试过,所以可能是错误的,或者可能不是您想要的结果,希望它能有所帮助:

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

这完全取决于您想要实现的目标,但我们假设:

  • 所有
    firstAsyncCall()
    调用成功完成后,将执行
    secondAsyncCall()
  • “其他异步内容”应该在
    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()链接进一步的操作

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