【发布时间】:2013-01-24 11:34:26
【问题描述】:
我是reading about Deferreds and Promises,并且经常遇到$.when.apply($, someArray)。我有点不清楚这到底是做什么的,正在寻找 一行 完全有效的解释(不是整个代码 sn-p)。这是一些上下文:
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');
}
【问题讨论】:
-
.done()在这种情况下可以用来代替.then,仅供参考 -
fwiw,有一个下划线的延迟端口允许将单个数组传递给
_.when,因此您不需要使用apply -
了解更多关于
.apply的信息:developer.mozilla.org/en-US/docs/JavaScript/Reference/…。 -
OP 在他的第一句话中提到的文章已经移动了位置 - 现在在:flaviocopes.com/blog/deferreds-and-promises-in-javascript。
标签: javascript jquery asynchronous promise