我使用 $.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/