0

我无法将已完成的 Deferred 与 $.when() 同步。我想在所有延期完成时收到通知,无论是解决还是失败。

我的问题是 when().always() 最初触发失败并且不等待其他延迟完成。不确定它是否是一个错误。

我做了一个例子,这是一个 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
4

2 回答 2

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

资源

或者有人认为像

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");
});

资源

于 2012-09-12T17:37:21.930 回答
0

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

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

http://jsfiddle.net/LTsLJ/

于 2012-09-13T08:52:16.500 回答