我是 reading about Deferreds and Promises并不断遇到 $.when.apply($, someArray)
。我有点不清楚这到底是做什么的,正在寻找 one line 完全有效的解释(不是整个代码片段)。这是一些上下文:
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
)。
那么,让我们采用$.when
。它过去常说“当所有这些 promise 都得到解决时……做点什么”。它需要无限(可变)数量的参数。
在你的例子中,你有一系列的 promise ;您不知道要向 $.when
传递多少参数。将数组本身传递给 $.when
是行不通的,因为它希望它的参数是 promise ,而不是数组。
这就是 .apply
的用武之地。它获取数组,并调用 $.when
并将每个元素作为参数(并确保 this
设置为 jQuery
/$
),所以一切正常:-)
关于javascript - $.when.apply($, someArray) 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777031/