Looping through jQuery Deferreds after all promises have been called
Solution 1:
Am I using the wrong approach for deferreds and promises?
Yes. In the asynchronous callback you should not access promises
, but only the callback arguments. The return promise of $.when
does resolve with an array of the .resolve()
parameters for each of the promises in the array - you can loop over the arguments
object to access the results:
$.when.apply($, promises).then(function () {
for (var i = 0; i < arguments.length; i++) {
var singleresult = arguments[i][0];
console.log(singleresult);
}
});
Solution 2:
you can use the arguments object to refer all the values returned by the promise objects
$.when.apply($, promises).then(function () {
for (var i = 0; i < arguments.length; i++) {
var data = arguments[i][0];
// PROBLEM HERE: I need to get the
// result from my resolved Deferred
// of every single promise object
console.log(data);
}
});
Solution 3:
I see you heve accepted an answer but you might like to be aware that your handleFileSelect
method can be significantly simplified as follows
handleFileSelect: function(e) {
var promises = $.map(e.target.files, function(file) {
return FileProcessor.read(file);
});
$.when.apply(window, promises).then(function() {
$.each(arguments, function(i, a) {
console.log(a[0]);
});
});
},
Of course it will get more complicated again when you flesh out the result handling but this should give you a nice concise basis.