How to use async/await with a forEach loop with Node.js?

Sometimes, we want to use async/await with a forEach loop with Node.js.

In this article, we’ll look at how to use async/await with a forEach loop with Node.js.

How to use async/await with a forEach loop with Node.js?

To use async/await with a forEach loop with Node.js, we can use the for-of loop.

For instance, we write

async function printFiles() {
  const files = await getFilePaths();

  for (const file of files) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

to loop through the files array and call fs.readFile on the file.

The await keyword will wait for the promise returned by readFile to resolve before moving to the next iteration.

Conclusion

To use async/await with a forEach loop with Node.js, we can use the for-of loop.