Reputation: 1538
I have an array of Deferred objects, which I'm trying to map to their resolved values once they complete. I want to return the array when everything finishes resolving.
Here's what I have so far:
$.when.apply(null, deferredArray)
.pipe(function(){
return deferredArray;
});
Unfortunately, this returns the array of Deferred objects in the resolved state.
Is there any way I can directly access the resolved elements? I know I can chain .then
and .pipe
on the resolved array of Deferred objects individually, but this doesn't work well for my purposes.
Upvotes: 2
Views: 688
Reputation: 1538
Here is a hacky solution:
extractDeferredArray = function(array) {
var deferred, extract, ret;
ret = [];
extract = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
deferred = array[_i];
_results.push(deferred.then(function(value) {
return ret.push(value);
}));
}
return _results;
})();
// Make sure our .then methods have completed
return $.when.apply(null, extract).pipe(function() {
return ret;
});
};
Seems kind of awkward to have to do this.
Upvotes: -1
Reputation: 816590
Deferred objects are not designed to return any values. You have to handle the results in callbacks.
The results are passed as arguments to the done
, fail
or pipe
callbacks:
$.when.apply(null, deferredArray).then(function(){
// arguments[0] is the result of the first deferred object
// arguments[1] is the result of the second deferred object
// ...
// or simple pass it to a function that needs the results:
someFunction(arguments);
});
Of couse in you can also just set that function as callback:
$.when.apply(null, deferredArray).then(someFunction);
Upvotes: 2