亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

$ .when.apply($,someArray)有什么作用?

$ .when.apply($,someArray)有什么作用?

搖曳的薔薇 2019-11-06 10:40:35
我正在閱讀關于遞延和承諾的書,并不斷遇到$.when.apply($, someArray)。我不清楚這到底是做什么的,正在尋找一種解釋,說明哪一行可以正常工作(而不是整個代碼段)。這里是一些上下文:var data = [1,2,3,4]; // the ids coming back from serviceAvar 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');}
查看完整描述

3 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

.apply用于調用帶有參數數組的函數。它接受數組中的每個元素,并將每個元素用作函數的參數。 .apply也可以this在函數內部更改context()。


因此,讓我們來$.when。過去常說“當所有這些諾言都得到解決時……采取行動”。它需要無限(可變)數量的參數。


就您而言,您有各種各樣的承諾;您不知道要傳遞給多少參數$.when。將數組本身傳遞給$.when是行不通的,因為它期望參數是promise,而不是數組。


就是這樣.apply了。它接收數組,并$.when以每個元素作為參數進行調用(并確保將this其設置為jQuery/ $),因此一切正常:-)


查看完整回答
反對 回復 2019-11-06
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

$ .when使用任意數量的參數,并在所有這些參數均已解析后解析。


anyFunction .apply(thisValue,arrayParameters)調用函數anyFunction設置其上下文(thisValue將是該函數調用內的this),并將arrayParameters中的所有對象作為單獨的參數傳遞。


例如:


$.when.apply($, [def1, def2])

是相同的:


$.when(def1, def2)

但是應用調用的方法允許您傳遞數量未知的參數數組。(在您的代碼中,您說的是數據來自服務,這是調用$ .when的唯一方法)


查看完整回答
反對 回復 2019-11-06
?
慕妹3146593

TA貢獻1820條經驗 獲得超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');

}


查看完整回答
反對 回復 2019-11-06
  • 3 回答
  • 0 關注
  • 592 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號