jquery - 将延迟数组与 jQuery.when() 一起使用

标签 jquery jquery-deferred .when

我使用 $.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!")
});

哪里出了问题? 谢谢。

最佳答案

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

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

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

这是一个工作 fiddle :http://jsfiddle.net/6MeM5/

另外:

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

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

关于jquery - 将延迟数组与 jQuery.when() 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14931004/

相关文章:

javascript - 如何使父 div 的 child 成为焦点而不是孙子 div?

javascript - 使用 javascript 设置过期日期

javascript - 如果不需要执行操作,则创建延迟

javascript - $.when(ajax 1, ajax 2, ajax3).always(ajax 1,ajax 2,ajax3) 在 3 个请求完成之前触发

jquery:当您将延迟对象传递到 "then"时会发生什么?

javascript - then 中的函数在 when 结束之前被调用

JavaScript/jQuery : control execution order (no ajax/php yet)

jquery - 将可拖动的 div 附加到另一个 div

Jquerymobile 添加动态可折叠 div

javascript - jQuery .when 未按预期与休息运算符一起工作