arrow_back Return to Posts

Async-Await in a Foreach Loop
By Godwin Udofia in October 2022 ~ JavaScript

The situation

Running asynchronous code within a forEach loop as shown in the snippet does not return the desired result.

 try {
    let posts = await loadPostsWithFrontMatter(postsPath);

    posts.forEach(async (post) => {
        const { slug, title, date, content } = posts[i];
      
        const browser = await puppeteer.launch();

        // ... a bunch of other awaits

        await browser.close();
    });

  } catch (error) {
    throw error;
  }

The problem

forEach loops do not wait for each promise to resolve. The loop actually finishes iterating before promises are resolved. You may end up trying to access values that are not available yet.

Solution

There are a number of ways to handle this issue. An extensive discussion of some of them can be found in this article.

However, using a simple for loop instead of a forEach loop takes care of this problem.

 try {
    let posts = await loadPostsWithFrontMatter(postsPath);

    for (var i = 0; i < posts.length; i++) {
      
      const { slug, title, date, content } = posts[i];
      
      const browser = await puppeteer.launch();

      // ... a bunch of other awaits

      await browser.close();
    }
  } catch (error) {
    throw error;
  }

Comments