将延迟与when同步

时间:2012-09-12 16:21:39

标签: jquery jquery-deferred

我在使用$ .when()同步已完成的Deferred时遇到了麻烦。 我希望在所有延期完成解决或失败后收到通知。

我的问题是当()。始终触发的always()失败并且不等待其他延迟完成。不确定这是不是一个bug。

我做了一个例子,这里是一个JsFiddle: http://jsfiddle.net/m3REv/

来自它的js代码:

/* our multiple deferred we'd like to sync. */
var def1 = $.Deferred();
var def2 = $.Deferred();
var def3 = $.Deferred();

def1.done( function() { logger.log('1 done');} ).fail( function() {logger.log('1 fail');} );
def2.done( function() { logger.log('2 done');} ).fail( function() {logger.log('2 fail');} );
def3.done( function() { logger.log('3 done');} ).fail( function() {logger.log('3 fail');} );

$.when( def1, def2, def3 ).then( function() {
    logger.log('w then');
} ).done( function() {
    logger.log('w done');
} ).fail( function() {
    logger.log('w fail');
} ).always( function() {
    logger.log('w always');
});


def1.reject();
def2.resolve();
def3.resolve();

,输出为:

1 fail
w fail
w always
2 done
3 done

2 个答案:

答案 0 :(得分:1)

解决方法:

var defCount = 3, state = 0;
var overallAlways = function () {
    if (++state < defCount) return;
    logger.log('correct always');
};

def1.done( function() { logger.log('1 done');} )
    .fail( function() {logger.log('1 fail');} )
    .always(overallAlways);
def2.done( function() { logger.log('2 done');} )
    .fail( function() {logger.log('2 fail');} )
    .always(overallAlways);
def3.done( function() { logger.log('3 done');} )
    .fail( function() {logger.log('3 fail');} )
    .always(overallAlways);

Source

或类似

function overallAlways(defObjects, callback) {
    var defCount = defObjects.length, state = 0;
    var alwaysCallback = function () {
        if (++state < defCount) return;
        callback.call(this);
    }
    $.each(defObjects, function (i, def) {
        def.always(alwaysCallback);
    });
}

var defs = [def1, def2, def3];
overallAlways(defs, function(){
    logger.log("overall always");
});

Source

答案 1 :(得分:0)

最后我写了一个插件,它是jQuery.when()的略微修改版本。我没有详尽地测试它,但它现在适用于小提琴和我的个人使用。

这里是插件的小提琴加上例子:

http://jsfiddle.net/LTsLJ/