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

我正在阅读关于递延和承诺的书,并不断遇到$.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');

}


一只甜甜圈
浏览 295回答 3
3回答

翻阅古今

.apply用于调用带有参数数组的函数。它接受数组中的每个元素,并将每个元素用作函数的参数。 .apply也可以this在函数内部更改context()。因此,让我们来$.when。过去常说“当所有这些诺言都得到解决时……采取行动”。它需要无限(可变)数量的参数。就您而言,您有各种各样的承诺;您不知道要传递给多少参数$.when。将数组本身传递给$.when是行不通的,因为它期望参数是promise,而不是数组。就是这样.apply了。它接收数组,并$.when以每个元素作为参数进行调用(并确保将this其设置为jQuery/ $),因此一切正常:-)

鸿蒙传说

$ .when使用任意数量的参数,并在所有这些参数均已解析后解析。anyFunction .apply(thisValue,arrayParameters)调用函数anyFunction设置其上下文(thisValue将是该函数调用内的this),并将arrayParameters中的所有对象作为单独的参数传递。例如:$.when.apply($, [def1, def2])是相同的:$.when(def1, def2)但是应用调用的方法允许您传递数量未知的参数数组。(在您的代码中,您说的是数据来自服务,这是调用$ .when的唯一方法)

喵喔喔

在这里,代码已完整记录。// 1. Declare an array of 4 elementsvar data = [1,2,3,4]; // the ids coming back from serviceA// 2. Declare an array of Deferred objectsvar processItemsDeferred = [];// 3. For each element of data, create a Deferred push push it to the arrayfor(var i = 0; i < data.length; i++){&nbsp; processItemsDeferred.push(processItem(data[i]));}// 4. WHEN ALL Deferred objects in the array are resolved THEN call the function//&nbsp; &nbsp; Note : same as $.when(processItemsDeferred[0], processItemsDeferred[1], ...).then(everythingDone);$.when.apply($, processItemsDeferred).then(everythingDone);&nbsp;// 3.1. Function called by the loop to create a Deferred object (data is numeric)function processItem(data) {&nbsp; // 3.1.1. Create the Deferred object and output some debug&nbsp; var dfd = $.Deferred();&nbsp; console.log('called processItem');&nbsp; // 3.1.2. After some timeout, resolve the current Deferred&nbsp; //in the real world, this would probably make an AJAX call.&nbsp; setTimeout(function() { dfd.resolve() }, 2000);&nbsp; &nbsp;&nbsp;&nbsp; // 3.1.3. Return that Deferred (to be inserted into the array)&nbsp; return dfd.promise();}// 4.1. Function called when all deferred are resolvedfunction everythingDone(){&nbsp; // 4.1.1. Do some debug trace&nbsp; console.log('processed all items');}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java