DEV Community

Why we cant use await inside forEach? and its workaround.

Husnain Mustafa on January 13, 2024

Have you ever tried using the await inside forEach? [].forEach(async(item) => { await doSomethingWith(item) }) Enter fullscreen mo...
Collapse
 
kurealnum profile image
Oscar

Awesome article! If you were curious, you can add syntax highlighting to your code snippets by adding the language after the opening backticks like so:

Image description

which produces

console.log("Hello World!")
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aminnairi profile image
Amin

You can also create your own helper function that does a similar job compared to Array.prototype.forEach. Here using a function declaration to not pollute the Array.prototype.

async function forEachAsync(array, asyncCallback) {
  if (!Array.isArray(array)) {
    throw new Error("First argument should be an array");
  }

  if (typeof asyncCallback !== "function") {
    throw new Error("Second argument should be a function");
  }

  let index = 0;

  for await (const item of array) {
    await asyncCallback(item, index++, array);
  }
}

const urls = [
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/posts",
  "https://jsonplaceholder.typicode.com/photos",
];

try {
  forEachAsync(urls, async (url, index) => {
    const response = await fetch(`${url}/${index + 1}`);
    const json = await response.json();

    console.log(json);
  });
} catch (error) {
  console.error(error);
}
Enter fullscreen mode Exit fullscreen mode

Not as sexy as polluting the Array.prototype but it does the trick as expected.

Collapse
 
pavelee profile image
Paweł Ciosek

Thank you! 🙏

Collapse
 
raguay profile image
Richard Guay

Been there and done that!