为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只甜甜圈 2019-12-11 10:09:10
我正在阅读关于递延和承诺的书,并不断遇到$.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 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

.apply用于调用带有参数数组的函数。它接受数组中的每个元素,并将每个元素用作函数的参数。 .apply也可以this在函数内部更改context()。


因此,让我们来$.when。过去常说“当所有这些诺言都得到解决时……采取行动”。它需要无限(可变)数量的参数。


就您而言,您有各种各样的承诺;您不知道要传递给多少参数$.when。将数组本身传递给$.when是行不通的,因为它期望参数是promise,而不是数组。


就是这样.apply了。它接收数组,并$.when以每个元素作为参数进行调用(并确保将this其设置为jQuery/ $),因此一切正常:-)



查看完整回答
反对 回复 2019-12-12
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

$ .when使用任意数量的参数,并在所有这些参数均已解析后解析。


anyFunction .apply(thisValue,arrayParameters)调用函数anyFunction设置其上下文(thisValue将是该函数调用内的this),并将arrayParameters中的所有对象作为单独的参数传递。


例如:


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

是相同的:


$.when(def1, def2)

但是应用调用的方法允许您传递数量未知的参数数组。(在您的代码中,您说的是数据来自服务,这是调用$ .when的唯一方法)



查看完整回答
反对 回复 2019-12-12
?
喵喔喔

TA贡献1735条经验 获得超5个赞

在这里,代码已完整记录。


// 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-12-12
  • 3 回答
  • 0 关注
  • 294 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信