顺序执行Jquery Defers

时间:2016-04-13 19:20:57

标签: javascript jquery jquery-deferred

在下面的代码中,我想在while循环中顺序执行saveBulkUploadSinglePacket方法,这意味着在完成当前数据包后处理下一个数据包。如何实现这一点。

var saveBulkUploadSinglePacket = function(){
while (packetCount<=bulkUploadPackets.length){
            $.when(saveBulkUploadSinglePacket(modelToSave)).done(function(arguments){
                saveBulkUploadPackets.push(arguments);
                packetCount++;
            });

        }
  return saveBulkUploadPackets;

}



var saveBulkUploadSinglePacket = function(modelToSave){
        var defer = $.Deferred();
        $.when(new SaveBulkUpload().save(modelToSave)).done(function(arguments){
            defer.resolve(arguments);
        }).fail(function(errorObj){  
           defer.reject(errorObj);
        });

        return defer.promise();

    }

2 个答案:

答案 0 :(得分:1)

说“完成承诺时执行x”的标准方法是promise.then()。跟踪循环外的var中的当前承诺,并使用.then()将每个调用附加到上一个承诺:

var saveBulkUploadSinglePacket = function(){
    var lastPromise = $.when();
    while (packetCount<=bulkUploadPackets.length){
        lastPromise = (
           lastPromise
             .then(function(){
                 // make sure saveBulkUploadSinglePacket returns a promise
                 return saveBulkUploadSinglePacket(modelToSave));
             })
             .then(function(){
                 saveBulkUploadPackets.push(arguments);
                 packetCount++;
                 // return a resolved promise
                 return $.when();
             })
        );
    }
    lastPromise.resolve(saveBulkUploadPackets);
    return lastPromise;
}

在函数结束时,我使用所需的返回值解析了最终的promise,然后返回了promise。这样,您可以调用saveBulUploadSinglePacket().then(...)等待所有承诺完成并处理结果。

答案 1 :(得分:0)

要按顺序保存您的pets,请使用Array.prototype.reduce()非常简洁地构建.then()链,如下所示:

var saveBulkUploadPackets = function(packets) {
    return packets.reduce(function(promise, paket) {
        return promise.then(function(results) {
            return (new SaveBulkUpload()).save(paket).then(function(res) {
                return results.concat(res);
            });
        });
    }, $.when([]));
}

并且这样打电话:

saveBulkUploadPackets(bulkUploadPackets).then(function(results) {
    // All done.
    // use/log the `results` array here.
});