jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – jquery deferred – 等到两个电话完成大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在两次ajax调用完成后,我正在寻找一种回调方式:
$.when(
    call1(),call2()
).always(function() {
    // Here I want to be sure the two calls are done and to get their responses 
);

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

如何等待两个呼叫完成(成功或失败)?

解决方法

这是一个应该做的诀窍:
$.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 @R_516_4895@ = [];
        var successes = [];

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

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

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

    return result;
}

查看this Fiddle看看它是如何工作的.

基本上,等待所有Deferreds完成,无论他们是否失败,并收集所有的结果.如果我们有失败,返回的Deferred将失败并列出所有故障,否则解决所有成功.

大佬总结

以上是大佬教程为你收集整理的javascript – jquery deferred – 等到两个电话完成全部内容,希望文章能够帮你解决javascript – jquery deferred – 等到两个电话完成所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。