Reputation: 3367
I have an async call inside a loop, and I would like to resolve the entire function when all the deferreds have been resolved.
var deferred = JQuery.Dferred();
for (var x in array){
async(x).then(function(result){
console.log(result);
})
}
deferred.promise();
My question is: How could I make the deferred.resolve() when the loop has finished?
Upvotes: 0
Views: 367
Reputation: 57719
Use when
with an Array of promises:
function waitForAll(array) {
var promises = [];
for (var x in array){
promises.push(async(x).then(function(result){
console.log(result);
return result; // don't forget to propagate the result
}));
}
return jQuery.when.apply(null, promises);
}
Use the magic variable arguments
to get the results.
waitForAll(array).then(function () {
var result = arguments;
for (var index in array) {
console.log(result[index]);
}
}
jQuery's Promise library is messy at best (I'm sure they have their reasons). If you want to learn more about Promises look at Promises/A+ standard.
Upvotes: 3
Reputation: 973
Could you please try .....
var deferred = $.Deferred();
for (var x in array){
async(x).then(function(result){
console.log(result);
deferred.resolve(result);
})
}
return deferred.promise();
Upvotes: 0