Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *