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.