顺序执行多个Deferred对象,一个完成后或失败状态启动另一个

时间:2014-03-21 19:08:31

标签: javascript jquery jquery-deferred

我遇到顺序执行Deferred对象的问题。完成一个之后,另一个应该开始。

我的功能是这样的:

    delete_items:function(objects,type){
        var deferred = $.Deferred(),
        deletePromises = [],           //Store All deferred objects in this array.
        success = [],                  //if success push object in this array
        fail = [],                     //if failure push objects in this array


        objects.forEach(function (object) {

            //pushing the objects in the array 
            deletePromises.push(
                       del(object.id)              // this is a deferred function. 
                       .done(function (){
                          success.push(object);
                       }).fail(function () {
                          fail.push(object);
                       }));
                    });

        //executing them but this doesn't wait for one object to complete before executing another

        $.when.apply(this, deletePromises).done(function () {
            deferred.resolve(success);
        }).fail(function (reason) {
            deferred.reject(reason, "DELETE");
        });
        return deferred.promise();

    }

我希望deletePromises[]中的对象根据它们的索引执行,当一个对象返回成功或失败时,应该执行该数组中的下一个对象。

任何帮助都会很棒。

0 个答案:

没有答案