Mario Levrero
Mario Levrero

Reputation: 3367

Resolve deferred when loop ends

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

Answers (2)

Halcyon
Halcyon

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

Vishal Patel
Vishal Patel

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

Related Questions