3 回答

TA貢獻1856條經(jīng)驗 獲得超5個贊
.apply用于調(diào)用帶有參數(shù)數(shù)組的函數(shù)。它接受數(shù)組中的每個元素,并將每個元素用作函數(shù)的參數(shù)。 .apply也可以this在函數(shù)內(nèi)部更改context()。
因此,讓我們來$.when。過去常說“當(dāng)所有這些諾言都得到解決時……采取行動”。它需要無限(可變)數(shù)量的參數(shù)。
就您而言,您有各種各樣的承諾;您不知道要傳遞給多少參數(shù)$.when。將數(shù)組本身傳遞給$.when是行不通的,因為它期望參數(shù)是promise,而不是數(shù)組。
就是這樣.apply了。它接收數(shù)組,并$.when以每個元素作為參數(shù)進行調(diào)用(并確保將this其設(shè)置為jQuery/ $),因此一切正常:-)

TA貢獻1911條經(jīng)驗 獲得超7個贊
$ .when使用任意數(shù)量的參數(shù),并在所有這些參數(shù)均已解析后解析。
anyFunction .apply(thisValue,arrayParameters)調(diào)用函數(shù)anyFunction設(shè)置其上下文(thisValue將是該函數(shù)調(diào)用內(nèi)的this),并將arrayParameters中的所有對象作為單獨的參數(shù)傳遞。
例如:
$.when.apply($, [def1, def2])
是相同的:
$.when(def1, def2)
但是應(yīng)用調(diào)用的方法允許您傳遞數(shù)量未知的參數(shù)數(shù)組。(在您的代碼中,您說的是數(shù)據(jù)來自服務(wù),這是調(diào)用$ .when的唯一方法)

TA貢獻1820條經(jīng)驗 獲得超9個贊
在這里,代碼已完整記錄。
// 1. Declare an array of 4 elements
var data = [1,2,3,4]; // the ids coming back from serviceA
// 2. Declare an array of Deferred objects
var processItemsDeferred = [];
// 3. For each element of data, create a Deferred push push it to the array
for(var i = 0; i < data.length; i++){
processItemsDeferred.push(processItem(data[i]));
}
// 4. WHEN ALL Deferred objects in the array are resolved THEN call the function
// Note : same as $.when(processItemsDeferred[0], processItemsDeferred[1], ...).then(everythingDone);
$.when.apply($, processItemsDeferred).then(everythingDone);
// 3.1. Function called by the loop to create a Deferred object (data is numeric)
function processItem(data) {
// 3.1.1. Create the Deferred object and output some debug
var dfd = $.Deferred();
console.log('called processItem');
// 3.1.2. After some timeout, resolve the current Deferred
//in the real world, this would probably make an AJAX call.
setTimeout(function() { dfd.resolve() }, 2000);
// 3.1.3. Return that Deferred (to be inserted into the array)
return dfd.promise();
}
// 4.1. Function called when all deferred are resolved
function everythingDone(){
// 4.1.1. Do some debug trace
console.log('processed all items');
}
添加回答
舉報