Filipe Aleixo
Filipe Aleixo

Reputation: 4244

How to await promise function inside nested maps?

Suppose I have the following:

async function getReactionScores(userReactions) {
  const reactionsWithSharesPromises = userReactions.map((reactions) => {
    return {
      emoji: reactions.emoji,
      shares: reactions.users.map(async (user) => {
        return {
          username: user.username,
          // Just as an example of something to wait for
          shares: await sleep(1, user.id),
        };
      }),
    };
  });

}

function sleep(time, userID) {
  return new Promise((resolve) => setTimeout(resolve(userID), time));
}

How do I await for all the promises inside the second map to resolve? If it was only one map, I could do Promise.all, but promise all is not recursive.

Upvotes: 0

Views: 563

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You will need 2 Promise.all

async function getReactionScores(userReactions) {
  const reactionsWithSharesPromises = await Promise.all(userReactions.map(async (reactions) => {
    return {
      emoji: reactions.emoji,
      shares: await Promise.all(reactions.users.map(async (user) => {
        return {
          username: user.username,
          // Just as an example of something to wait for
          shares: await sleep(1, user.id),
        };
      })),
    };
  }));
}

Upvotes: 1

Related Questions