问题描述
我遇到了一个数组中有多个 JQuery Promise 的情况
I run into the situation where I have multiple JQuery Promises in an Array
var arrayOfPromises = [ $.Deferred(), $.Deferred(), $.Deferred(), $.Deferred() ]
并且需要把它变成一个数组的 JQuery Promise
and need to turn it into a JQuery Promise of an Array
var promiseOfArray = someTransform(arrayOfPromises)
在哪里
promiseOfArray.done(function(anArray){
alert(anArray.join(","));
});
使用文本创建警报
结果1,结果2,结果3,结果4
result1,result2,result3,result4
我目前在coffeescript中将someTransform
定义为
I currently define someTransform
in coffeescript as
someTransform = (arrayOfPromises) ->
$.when(arrayOfPromises...).pipe (promises...) ->
promises
转换成下面的javascript
which transforms to the following javascript
var someTransform,
__slice = [].slice;
someTransform = function(arrayOfPromises) {
return $.when.apply($, arrayOfPromises).pipe(function() {
var promises;
promises = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return promises;
});
};
这是我正在寻找的结果的 jsFiddle.
我想知道是否有更好(更短、更简洁)的方式来定义 someTransform
以达到相同的结果?
I was wondering if there is a better(shorter,cleaner) way to define someTransform
to achieve the same result?
推荐答案
你可以应用 数组作为 $.when
的参数.
You can just apply the array as the arguments to $.when
.
var promiseOfArray = $.when.apply($, arrayOfPromises);
为了更清楚地使用这个,我喜欢在 $
中添加一个方法:
To make the usage of this clearer, I like adding a method to $
:
$.whenall = function(arr) { return $.when.apply($, arr); };
现在你可以这样做了:
$.whenall([deferred1, deferred2, ...]).done(...);
<小时>
更新: 默认情况下,done
处理程序将每个结果作为单独的参数传递;你没有得到一个结果数组.
Update: By default, the done
handler gets each result passed as a separate argument; you don't get an array of results.
由于您需要处理任意数量的 Deferred,您可以使用特殊的隐式 arguments
对象循环遍历结果.
Since you need to handle an arbitrary number of Deferreds, you can use the special implicit arguments
object to loop over the results.
$.whenall([d1, d2, ...]).done(function() {
for (var i = 0; i < arguments.length; i++) {
// do something with arguments[i]
}
});
如果你真的只是想加入你所有延迟的字符串结果,我们可以使用一个小的数组黑客.arguments
类似于数组,但不是 Array
:
If you really just want to join the string result of all your Deferreds, we can employ a little array hackery. arguments
is array-like, but is not an Array
:
$.whenall([d1, d2, ...]).done(function() {
alert(Array.prototype.join.call(arguments, ','));
});
<小时>
如果您想向 done
回调返回一组结果,我们可以调整 whenall
去做:
If you want to return an array of results to your done
callback, we can tweak whenall
to do it:
$.whenall = function(arr) {
return $.when.apply($, arr).pipe(function() {
return Array.prototype.slice.call(arguments);
});
};
这篇关于将 JQuery Promise 数组转换为数组的 JQuery Promise 的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!