javascript - $.when.apply($, someArray) 是做什么的?

标签 javascript jquery asynchronous promise

我是 reading about Deferreds and Promises并不断遇到 $.when.apply($, someArray)。我有点不清楚这到底是做什么的,正在寻找 one line 完全有效的解释(不是整个代码片段)。这是一些上下文:

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用于调用带有参数数组的函数。它获取数组中的每个元素,并将每个元素用作函数的参数。 .apply 还可以更改函数内的上下文 (this)。

那么,让我们采用$.when。它过去常说“当所有这些 promise 都得到解决时……做点什么”。它需要无限(可变)数量的参数。

在你的例子中,你有一系列的 promise ;您不知道要向 $.when 传递多少参数。将数组本身传递给 $.when 是行不通的,因为它希望它的参数是 promise ,而不是数组。

这就是 .apply 的用武之地。它获取数组,并调用 $.when 并将每个元素作为参数(并确保 this 设置为 jQuery/$),所以一切正常:-)

关于javascript - $.when.apply($, someArray) 是做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777031/

相关文章:

php - jquery json循环数据 - 只是无法弄清楚这一点

node.js - NodeJs 与 Mongoose - 嵌套查询异步问题

c++ - boost .Asio : Async operations timeout

具有并发性的 Python 线程

Javascript - 删除 split 方法

javascript - 如何在javascript中将数据加载到特定的输入值?

javascript - 导航栏表现奇怪

jquery - 从元素中删除数据属性

javascript - Angular 如何在我的情况下设置服务

jquery - Bootstrap 轮播淡入淡出过渡