Using an array of deffered with jQuery.when()

微笑、不失礼 提交于 2019-12-08 06:22:32

问题


I'm using $.when to run 2 functions prior to some other logic. Now, in several cases I need to run a different set of functions prior to doing that same logic, so I wanted to pass an array of the functions to $.when, but couldn't make it run.

Something like:

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

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

But this doesn't work and the only thing written to the console is "DONE!". I read the following How do you work with an array of jQuery Deferreds?, but the following behaves the same:

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

What's wrong there? Thanks.


回答1:


Your inputs to $.when aren't of type Deferred, which is the expected input type for the function - http://api.jquery.com/jQuery.when/

At the simplest level, you could construct Deferred types with your functions as the beforeStart construction parameters. Like:

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

Here's a working fiddle: http://jsfiddle.net/6MeM5/

Additionally:

If you're just trying to execute each function in an array of functions, you don't need to get Deferred involved. Just iterate the array using $.each, like:

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


来源:https://stackoverflow.com/questions/14931004/using-an-array-of-deffered-with-jquery-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!