DEV Community

Discussion on: Async/Await and the forEach Pit of Despair

Collapse
 
vinno97 profile image
Vincent Brouwers

I've solved this problem before by using Array#reduce to basically build a big Promise chain.

It's something like

await posts.data.reduce((prev, curr) => prev.then(async post => {
    let user = await axios(`${baseURL}/users/${post.userId}`);
    console.log(user.data.name);
}), Promise.resolve()) 

If I only need the result to ordered and don't care about the actual execution order, I use Array#map with Promise#all

const result = Promise.all(posts.data.map(async post => await axios(`${baseURL}/users/${post.userId}`))) 

(in this example both the async and await can be left out since only the plain promises get used, but it should get the thought across)