【问题标题】:Using an array of deffered with jQuery.when()使用带有 jQ​​uery.when() 的 deferred 数组
【发布时间】:2013-02-02 13:42:08
【问题描述】:

我使用$.when 在其他一些逻辑之前运行 2 个函数。现在,在某些情况下,我需要在执行相同逻辑之前运行一组不同的函数,因此我想将一组函数传递给 $.when,但无法使其运行。

类似:

function funcA(){
    console.log("funcA");
}
function funcB(){
    console.log("funcB")
}
var funcArr = [funcA, funcB];

$.when(funcArr).then(function(){
    console.log("DONE!");
});

但这不起作用,写入控制台的唯一内容是“完成!”。 我阅读了以下How do you work with an array of jQuery Deferreds?,但以下行为相同:

$.when.apply($, funcArr).then(function(){
    console.log("DONE!")
});

那里有什么问题? 谢谢。

【问题讨论】:

    标签: jquery jquery-deferred .when


    【解决方案1】:

    您对 $.when 的输入不是 Deferred 类型,这是函数的预期输入类型 - http://api.jquery.com/jQuery.when/

    在最简单的级别上,您可以使用您的函数作为beforeStart 构造参数来构造Deferred 类型。喜欢:

    var funcArr = [$.Deferred(funcA), $.Deferred(funcB)];
    

    这是一个有效的小提琴:http://jsfiddle.net/6MeM5/

    另外:

    如果您只是尝试执行函数数组中的每个函数,则无需让Deferred 参与其中。只需使用$.each 迭代数组,例如:

    $.each(funcArr, function(){
        this();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2022-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多