Search code examples
javascriptasync-awaites6-promise

How to use promise.all with forEach in javascript?


I am making https requests in parallel for a given list of ids:

const posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));

This returns me an array of arrays (because fetchUserPosts returns a list):

[[{...post1Data}, {...post2Data}], [], [{...post3Data}], [{...post4Data}]]

And I want a plain list with all the posts.

Any ideas? I suppose I have to play with Promise.all and forEach but this doesn't work because I need an array of promises for the Promise.all argument...

CODE EXAMPLE

 const usersIds = [1, 2, 3, 4];

 (async () => {
     const posts = await Promise.all(usersIds.map(userId => fetchUserPost(userId)));

     console.log(posts);
 })();

 function fetchUserPost(userId) {
    return new Promise((resolve) => resolve([{ owner: userId }, { owner: userId } ]));
 }

Solution

  • After you await you can flat the list

    let posts = await Promise.all(usersIds.map(userId => fetchUserPosts(userId)));
    posts = posts.flat();