在jQuery.when()中使用有延迟的数组 [英] Using an array of deffered with jQuery.when()

查看:116
本文介绍了在jQuery.when()中使用有延迟的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

类似的东西:

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

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

但是这不起作用,唯一写入控制台的内容是完成!". 我阅读了以下如何使用一系列jQuery Deferreds?,但以下行为相同:

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!")
});

那是怎么了? 谢谢.

推荐答案

您对$.when的输入的类型不是Deferred,这是该函数的预期输入类型-

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

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

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

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

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

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

此外:

如果您只是想执行功能数组中的每个功能,则不需要参与Deferred.只需使用$.each迭代数组即可,例如:

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();
});

这篇关于在jQuery.when()中使用有延迟的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆