jquery deferred - 等到两个调用完成

Nao*_*aor 10 javascript jquery jquery-deferred

我正在寻找一种方法在两个ajax调用完成后进行回调:

$.when(
    call1(),
    call2()
).always(function() {
    // Here I want to be sure the two calls are done and to get their responses 
);
Run Code Online (Sandbox Code Playgroud)

问题是其中一个调用可能会失败.所以,在我的代码中,总是会调用它而不等待另一个调用.

我怎样才能等待两个完成的呼叫(成功或失败)?

Daf*_*aff 11

这是应该做的事情:

$.whenAllDone = function() {
    var deferreds = [];
    var result = $.Deferred();

    $.each(arguments, function(i, current) {
        var currentDeferred = $.Deferred();
        current.then(function() {
            currentDeferred.resolve(false, arguments);
        }, function() {
            currentDeferred.resolve(true, arguments);
        });
        deferreds.push(currentDeferred);
    });

    $.when.apply($, deferreds).then(function() {
        var failures = [];
        var successes = [];

        $.each(arguments, function(i, args) {
            // If we resolved with `true` as the first parameter
            // we have a failure, a success otherwise
            var target = args[0] ? failures : successes;
            var data = args[1];
            // Push either all arguments or the only one
            target.push(data.length === 1 ? data[0] : args);
        });

        if(failures.length) {
            return result.reject.apply(result, failures);
        }

        return result.resolve.apply(result, successes);
    });

    return result;
}
Run Code Online (Sandbox Code Playgroud)

看看这个小提琴,看看它是如何工作的.

基本上,无论是否失败,它都会等待所有Deferreds完成并收集所有结果.如果我们有失败,则返回的Deferred将失败并显示所有失败的列表,否则将解除所有成功.