Lonnie Best
Lonnie Best

Reputation: 11399

Using Await While Looping a Map Object

How can you iterate over each value in a Map, in manner where await will be honored in the body of that loop?

Upvotes: 1

Views: 1702

Answers (1)

Lonnie Best
Lonnie Best

Reputation: 11399

I ultimately used map.values() within a for await loop.

Here's a contrived example that showcases await working within a loop:

async function delay(ms)
{
  console.log(`Waiting ${ms} milliseconds . . .`);
  return new Promise((resolve)=>{ setTimeout(resolve, ms); });
}

async function main()
{
  let map = new Map([[1,"A"],[2,"B"],[3,"C"]]);

  for await (const value of map.values())
  {
          await delay(2000);
          console.log(value);
  }
}
main();

Upvotes: 3

Related Questions