Categories
JavaScript Answers

How to wait for .forEach() to complete with JavaScript?

Spread the love

Sometimes, we want to wait for .forEach() to complete with JavaScript.

In this article, we’ll look at how to wait for .forEach() to complete with JavaScript.

How to wait for .forEach() to complete with JavaScript?

To wait for .forEach() to complete with JavaScript, we should replace forEach with a for-of loop.

For instance, we write

const myAsyncLoopFunction = async (array) => {
  const allAsyncResults = [];

  for (const item of array) {
    const asyncResult = await asyncFunction(item);
    allAsyncResults.push(asyncResult);
  }

  return allAsyncResults;
};

to define the myAsyncLoopFunction function.

In it, we use a for-of loop to loop through the array.

And we use await to wait for the promise returned by asyncFunction to finish before allAsyncResults.push is called in each iteration.

Conclusion

To wait for .forEach() to complete with JavaScript, we should replace forEach with a 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 *