jQuery摆脱嵌套的ajax函数

时间:2014-02-15 01:29:22

标签: javascript jquery ajax asynchronous callback

在我的JS中,我需要用AJAX获取3个文件的内容,然后做一些代码。这导致了一个相当奇怪的嵌套异步函数创建。任何时候我都在使用异步函数,这个丑陋的嵌套出现了。

当我真的只想等待它们各自完成时,如何避免嵌套功能? (如果有帮助,我正在使用jQuery)

 function loadFilesAndDoStuff() {
    $.get(firstFile, function(first_file_data) {
      $.get(secondFile, function(second_file_data) {
        $.get(thirdFile, function(third_file_data) {
          someOtherAsyncFunction(function(combined_file_data) {
            // do some stuff with the "combined_file_data".
          });
        });
      });
    });
  }

2 个答案:

答案 0 :(得分:3)

以下是使用和不使用延迟的几种不同技术。在所有情况下,所有ajax调用都会启动,然后一些代码会跟踪所有ajax调用何时完成,并在调用完成时从调用中收集数据,这样当最后一个调用完成时,所有数据都可用。

您可以一次启动所有三个ajax调用,只需检查每个完成函数是否已完成,将结果存储在局部变量中,直到它们全部完成:

function loadFilesAndDoStuff() {
    var cntr = 3;
    var data1, data2, data3;

    function checkDone() {
        --cntr;
        if (cntr === 0) {
            // all three are done here
            someOtherFunction(combined_file_data);
        }
    }

    $.get(firstFile, function(data) {
        data1 = data;
        checkDone();
    });
    $.get(secondFile, function(data) {
        data2 = data;
        checkDone();
    });
    $.get(thirdFile, function(data) {
        data3 = data;
        checkDone();
    });
 }

或者,您可以将更多内容放在一个公共函数中,并将文件名数组传递给函数:

function loadFilesAndDoStuff(filesArray) {
    var results = [];
    var doneCnt = 0;

    function checkDone(index, data) {
        results[index] = data;
        ++doneCnt;
        if (doneCnt === filesArray.length) {
            // all results are in the results array now
        }
    }

    for (var i = 0; i < filesArray.length; i++) {
        results.push(null);
        $.get(filesArray[i], checkDone.bind(this, i));
    }
 }

使用Deferreds,您可以这样做:

function loadFilesAndDoStuff(filesArray) {
    var results = [];
    var deferreds = [];

    function doneOne(index, data) {
        results[index] = data;
    }

    for (var i = 0; i < filesArray.length; i++) {
        results.push(null);
        deferreds.push($.get(filesArray[i], doneOne.bind(this, i)));
    }
    $.when.apply($, deferreds).done(function() {
        // all ajax calls are done and results are available now
    });
}

或者,更简短的版本使用deferreds为每个延迟保存来自成功处理程序的参数这一事实:

function loadFilesAndDoStuff(filesArray) {
    var deferreds = [];

    for (var i = 0; i < filesArray.length; i++) {
        deferreds.push($.get(filesArray[i]));
    }
    $.when.apply($, deferreds).done(function() {
        // all ajax calls are done and results are available now
        // arguments[0][0] is the data from the first $.get call
        // arguments[1][0] is the data from the second $.get call
        // and so on
    });

}

最后一个选项的工作演示:http://jsfiddle.net/jfriend00/5ppU4/

仅供参考,$.when()内部没有任何魔力。如果你查看它的jQuery代码,它只是保留一个计数器,当传递给它的参数都完成时(类似于我的前两个选项)。主要区别在于它使用了jqXHR对象的promise接口,而不是知道它是一个ajax调用。但从概念上讲,它也在做同样的事情。


这里还有一个使用我为处理多个延迟而编写的新对象。

function loadFilesAndDoStuff(filesArray) {
    var deferred = $.MultiDeferred().done(function() {
        // all ajax calls are done and results are available now
        // arguments[0][0] is the data from the first $.get call
        // arguments[1][0] is the data from the second $.get call
        // and so on
    });

    for (var i = 0; i < filesArray.length; i++) {
        deferred.add($.get(filesArray[i]));
    }
}

MultiDeferred代码是一个专门编写的jQuery插件,用于处理多个延迟完成时的通知,并且代码在此处:

jQuery.MultiDeferred = function(/* zero or more promises */) {

    // make the Deferred
    var self = jQuery.Deferred();

    var remainingToFinish = 0;
    var promises = [];
    var args = [];
    var anyFail = false;
    var failImmediate = false;

    function _add(p) {
        // save our index in a local variable so it's available in this closure later
        var index = promises.length;

        // save this promise
        promises.push(p);
        // push placeholder in the args array
        args.push([null]);

        // one more waiting to finish
        ++remainingToFinish;

        // see if all the promises are done
        function checkDone(fail) {
            return function() {
                anyFail |= fail;
                // make copy of arguments so we can save them
                args[index] = Array.prototype.slice.call(arguments, 0);
                --remainingToFinish;

                // send notification that one has finished
                self.notify.apply(self, args[index]);
                // if all promises are done, then resolve or reject
                if (self.state() === "pending" && (remainingToFinish === 0 || (fail && failImmediate))){
                    var method = anyFail ? "reject" : "resolve";
                    self[method].apply(self, args);
                }
            }
        }
        // add our own monitors so we can collect all the data
        // and keep track of whether any fail
        p.done(checkDone(false)).fail(checkDone(true));
    }

    // add a new promise
    self.add = function(/* one or more promises or arrays of promises */) {
        if (this.state() !== "pending") {
            throw "Can't add to a deferred that is already resolved or rejected";
        }
        for (var i = 0; i < arguments.length; i++) {
            if (arguments[i] instanceof Array) {
                for (var j = 0; j < arguments[i].length; j++) {
                    _add(arguments[i][j]);
                }
            } else {
                _add(arguments[i]);
            }
        }
        return this;
    }

    // get count of remaining promises that haven't completed yet
    self.getRemaining = function() {
        return remainingToFinish;
    }

    // get boolean on whether any promises have failed yet
    self.getFailYet = function() {
        return anyFail;
    }

    self.setFailImmediate = function(failQuick) {
        failImmediate = failQuick;
        return this;
    }

    // now process all the arguments
    for (var i = 0; i < arguments.length; i++) {
        self.add(arguments[i]);
    }
    return self;    
};

答案 1 :(得分:0)

创建每个所需文件的数组,然后循环遍历文件数组并在每次迭代时调用$.get,并让它调用组合函数,该函数将组合数据并进行计数检查,一旦达到计数呼叫回叫。

function loadData(files,callback){
    var combinedData = "";
    var count = 0;
    function combineFile(data){
       count++;
       combinedData += data;
       if(count==files.length-1){
          callback(combinedData);
       }
    }

    for(var i=0; i<files.length; i++){
       $.get(files[i],combineFile);
    }
}

loadData(["files1.txt","files2.txt","files3.txt"],function(data){
   console.log("Combined Data: ",data);
});