简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM