jQuery-$ .when延迟对象数组的语法 [英] JQuery - $.when syntax for array of Deferred objects
问题描述
这是我第一次使用$.when
,语法有困难.
我的代码类似于下面的简化示例.它可以工作(如果我简化时没有引起错误).
我的问题是我不知道customerIds
数组将包含的许多元素.
It is the first time I am using $.when
and I am having difficulty with the syntax.
I have code similar to simplified example below. It works (if I haven't caused an error when I simplified it).
My problem is that I don't know home many elements the customerIds
array would contain.
var customerIds = new [1, 2, 3];
$.when(
getCustomerData(customerIds[0]),
getCustomerData(customerIds[1]),
getCustomerData(customerIds[2])
).then(function() {
alert('success');
}).fail(function() {
alert('error');
});
function getCustomerData(int id) {
return new $.Deferred(function(defer) {
doSomeWork(id, defer);
}).promise();
}
我想按如下方式编写$.when
语句,但是很难正确使用语法.
I would like to write the $.when
statement as follows but having difficulty getting the syntax right.
$.when(
getCustomerDataCalls(customerIds),
).then(function() {
alert('success');
}).fail(function() {
alert('error');
});
getCustomerDataCalls
的实现方式为:
function getCustomerDataCalls(customerIds) {
var dfds = [];
for (var id in customerIds) {
dfds.push(new $.Deferred(function(defer) {
doSomeWork(id, defer);
}).promise());
}
return dfds;
}
不幸的是,我的实现出现了问题,我无法弄清哪里出了问题.我最好的猜测是返回Deferred
s
Unfortunately something is wrong with my implementation and I cannot work out where I am going wrong. My best guess is that something is going wrong when returning an array of Deferred
s
更新:
在lanzz提到我的人为例子已经返回Deferred之后,我更新了代码,更新了我的例子以包含doSomeWork
Update:
I updated the code after lanzz mentioned that my contrived example already returns a Deferred, I updated my example to include doSomeWork
推荐答案
是的,我也偶然发现了这一点:when
不允许轻易地传递数组.但是您可以使用apply
达到所需的结果.
Yes, I have stumbled upon this as well: when
does not easily allow to be passed an array. But you could use apply
to achieve the desired result.
$.when.apply($, getCustomerDataCalls(customerIds))
这篇关于jQuery-$ .when延迟对象数组的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!