Musical Shore
Musical Shore

Reputation: 1381

How to loop over async calls using promises

I have an array of values that I want to loop over and pass to an asynchronous call, like so:

_.each(ids,function(id){
    doAsync(id);
});

I want to wait until all asynchronous calls are complete and .then() do something. How can I accomplish this?

Upvotes: 0

Views: 34

Answers (1)

frontend_dev
frontend_dev

Reputation: 1719

You might want to use Promise.all:

var promises = [];
_.each(ids,function(id){
    promises.push(doAsync(id));
});
Promise.all(promises).then(...)

But of course each doAsync has to return a Promise in this case.

Upvotes: 2

Related Questions