Iterating through items and dealing with asynchronous logic (i.e. API calls) are probably two of the most common tasks we have to perform as JavaScript devs. In this article, we will discuss the best approaches to combine async/await and iterative logic. There will be a time when you would want to run async operations inside for loops (or any type of other loops). Let’s take a look at how to deal with such situations.

Reading Promises in sequence

Let’s say we have a list of files and we would like to read and log the contents of each file in the sequence. How would we do this? Well, we can use a **for … of the **loop inside an async function. Here’s the code snippet.

async function printFiles () {
  let fileNames = ['picard', 'kirk', 'geordy', 'ryker', 'worf'];
  for (const file of fileNames) {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }
}

💡 Be advised that if you want to read files in sequence you can not use a forEach loop.

#javascript #nodejs #javascript-development #web-development #javascript-tips

Using Async/await inside Loops In JavaScript
1.55 GEEK