本文介绍了什么是$ .when.apply($,的someArray)呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的承诺,并保持整个 $。when.apply($,的someArray)。我对这个东西不正是,查找一行的工作原理完全(而不是整个code段)的解释有点不清楚。下面是一些背景:

  VAR数据= [1,2,3,4]; //的ID从serviceA回来
变种processItemsDeferred = [];对于(VAR I = 0; I< data.length;我++){
  processItemsDeferred.push(processItem(数据由[i]));
}$ .when.apply($,processItemsDeferred)。然后(everythingDone);功能processItem(数据){
  变种DFD = $ .Deferred();
  的console.log('称为processItem');  //在现实世界中,这很可能会令一个AJAX调用。
  的setTimeout(函数(){dfd.resolve()},2000);  返回dfd.promise();
}功能everythingDone(){
  的console.log('处理的所有项目);
}


解决方案

<$c$c>.apply用于调用函数与参数数组。它需要在阵列中的每个元素,并使用各自的参数的功能。 。适用也可以改变一个函数里面的背景下(这个)。

那么,让我们来 $。当。它常说:当这些承诺都解决了......做什么。它需要的参数无限(变量)数量。

在你的情况,你有承诺的数组;你不知道你传递给 $多少参数。当。数组本身传递给 $。当是行不通的,因为它需要它的参数是承诺,而不是一个数组。

这就是。适用的用武之地。它采用的阵列,并呼吁 $。当每个元素参数(并确保在这个设置为的jQuery / $ ),这样的话所有的工作: - )

I'm reading about Deferreds and Promises and keep coming across $.when.apply($, someArray). I'm a little unclear on what this does exactly, looking for an explanation that one line works exactly (not the entire code snippet). Here's some context:

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');
}
解决方案

.apply is used to call a function with an array of arguments. It takes each element in the array, and uses each as a parameter to the function. .apply can also change the context (this) inside a function.

So, let's take $.when. It's used to say "when all these promises are resolved... do something". It takes an infinite (variable) number of parameters.

In your case, you have an array of promises; you don't know how many parameters you're passing to $.when. Passing the array itself to $.when wouldn't work, because it expects its parameters to be promises, not an array.

That's where .apply comes in. It takes the array, and calls $.when with each element as a parameter (and makes sure the this is set to jQuery/$), so then it all works :-)

这篇关于什么是$ .when.apply($,的someArray)呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:05