问题描述
我正在阅读关于 Deferreds 和 Promises 并不断遇到 $.when.apply($, someArray)
.我有点不清楚这到底是做什么的,正在寻找 一行 完全有效的解释(不是整个代码片段).这是一些上下文:
I'm reading about Deferreds and Promises and keep coming across $.when.apply($, someArray)
. I'm a little unclear on what this does exactly, looking for an explanation that one line works exactly (not the entire code snippet). Here's some context:
var data = [1,2,3,4]; // the ids coming back from serviceA
var processItemsDeferred = [];
for(var i = 0; i < data.length; i++){
processItemsDeferred.push(processItem(data[i]));
}
$.when.apply($, processItemsDeferred).then(everythingDone);
function processItem(data) {
var dfd = $.Deferred();
console.log('called processItem');
//in the real world, this would probably make an AJAX call.
setTimeout(function() { dfd.resolve() }, 2000);
return dfd.promise();
}
function everythingDone(){
console.log('processed all items');
}
推荐答案
.apply
用于调用带有参数数组的函数.它获取数组中的每个元素,并将每个元素用作函数的参数..apply
还可以更改函数内的上下文 (this
).
.apply
is used to call a function with an array of arguments. It takes each element in the array, and uses each as a parameter to the function. .apply
can also change the context (this
) inside a function.
那么,让我们以 $.when
为例.它习惯于说当所有这些承诺都得到解决时……做点什么".它需要无限(可变)数量的参数.
So, let's take $.when
. It's used to say "when all these promises are resolved... do something". It takes an infinite (variable) number of parameters.
就您而言,您有一系列承诺;你不知道你传递给 $.when
多少参数.将数组本身传递给 $.when
是行不通的,因为它希望它的参数是 promise,而不是数组.
In your case, you have an array of promises; you don't know how many parameters you're passing to $.when
. Passing the array itself to $.when
wouldn't work, because it expects its parameters to be promises, not an array.
这就是 .apply
的用武之地.它接受数组,并使用每个元素作为参数调用 $.when
(并确保 this
设置为 jQuery
/$
),然后一切正常:-)
That's where .apply
comes in. It takes the array, and calls $.when
with each element as a parameter (and makes sure the this
is set to jQuery
/$
), so then it all works :-)
这篇关于$.when.apply($, someArray) 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!