我是reading about Deferreds and Promises,并且不断遇到$.when.apply($, someArray)
。我有点不清楚这到底是什么,寻找一个解释,一行工作正好(不是整个代码片段)。下面是一些背景:
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'的'被用来在这种情况下,只是FYI – 2013-02-08 16:39:53
FWIW,有一个递延端口强调,允许通过一个单一的array to'_.when',所以你不需要使用'apply' – Eevee 2013-02-08 16:45:12
了解更多关于'.apply'的信息:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function /应用。 – 2013-02-08 16:48:38