上面的解决方法(谢谢!)没有正确解决取回提供给 deferredresolve()
方法的对象的问题,因为 jQuery使用单个参数而不是数组调用done()
和fail()
回调。这意味着我们必须使用arguments
伪数组来获取延迟数组返回的所有已解决/拒绝的对象,这很丑陋:
$.when.apply($,deferreds).then(function() {
var objects = arguments; // The array of resolved objects as a pseudo-array
...
};
因为我们传入了一个延迟数组,所以返回一个结果数组会很好。返回一个实际数组而不是伪数组也很好,这样我们就可以使用像Array.sort()
.
这里是通过激发溶液when.js的when.all()
方法,该方法解决了这些问题:
// Put somewhere in your scripting environment
if (typeof jQuery.when.all === 'undefined') {
jQuery.when.all = function (deferreds) {
return $.Deferred(function (def) {
$.when.apply(jQuery, deferreds).then(
// the calling function will receive an array of length N, where N is the number of
// deferred objects passed to when.all that succeeded. each element in that array will
// itself be an array of 3 objects, corresponding to the arguments passed to jqXHR.done:
// ( data, textStatus, jqXHR )
function () {
var arrayThis, arrayArguments;
if (Array.isArray(this)) {
arrayThis = this;
arrayArguments = arguments;
}
else {
arrayThis = [this];
arrayArguments = [arguments];
}
def.resolveWith(arrayThis, [Array.prototype.slice.call(arrayArguments)]);
},
// the calling function will receive an array of length N, where N is the number of
// deferred objects passed to when.all that failed. each element in that array will
// itself be an array of 3 objects, corresponding to the arguments passed to jqXHR.fail:
// ( jqXHR, textStatus, errorThrown )
function () {
var arrayThis, arrayArguments;
if (Array.isArray(this)) {
arrayThis = this;
arrayArguments = arguments;
}
else {
arrayThis = [this];
arrayArguments = [arguments];
}
def.rejectWith(arrayThis, [Array.prototype.slice.call(arrayArguments)]);
});
});
}
}
现在您可以简单地传入一组延迟/Promise并在您的回调中取回一组已解决/拒绝的对象,如下所示:
$.when.all(deferreds).then(function(objects) {
console.log("Resolved objects:", objects);
});