NodeJS async/await in loops

In this article, I will give you some ways to use await in loops. To start, we should write a example as below:

const func = async (data) => {
  return new Promise(resolve => {console.log(data)});
}

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

Let’s start by a loop over the testArray and try to call func on it:

const testAwaitLoop = async () => {
   testArray.foreach(item => {
      await func(item);
  });
}

This code will throw a syntax error:

Because we can not use await inside synchronous function (forEach is synchronous function). How to resolve it? By flowing, I give you 2 ways to fix this issue.

1. We use for..of construction

const testAwaitLoop = async () => {
   for(const item of testArray) {
      await func(item);
  };
}

The code will handle each item one by one in series.

2. We use map for array

const testAwaitLoop = async () => {
    const promises = testArray.map(func);
    await Promise.all(promises);
}

The code will handle each item in parallel.

That’s it all. Moreover, we have other ways for calling await in forEach, for, filter, reduce, etc. Please check more on the internet.
Thank you for reading!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s