lecture 9 of 140 completed

Async work in loops

forEach with an async callback does not wait. Use for...of to go one at a time, or map with Promise.all to go together.

What you'll learn

  • Why forEach does not wait for an async callback
  • How for...of with await runs steps one after another
  • How to choose between one at a time and all together

A test cleans up after itself. It deletes every loan it created and then checks that the list is empty. The check fails, and when someone looks a second later the list is empty.

function deleteLoan(id) {
  return Promise.resolve().then(() => {
    console.log("deleted loan " + id);
  });
}

async function cleanUp() {
  const ids = [7, 9];
  ids.forEach(async (id) => {
    await deleteLoan(id);
  });
  console.log("clean-up finished");
}

cleanUp();
clean-up finished
deleted loan 7
deleted loan 9

"clean-up finished" prints before anything is deleted.

forEach calls your callback once for each item and ignores what the callback returns. An async callback returns a promise. forEach does not look at it and does not wait for it.

The await inside the callback is real. It pauses that callback. It does not pause cleanUp, because await only pauses the function it is written in. This is the rule from the lecture on async and await, in the place where people most often forget it.

The language guarantees the order you see. forEach returns as soon as it has called each callback, and the code after an await always runs later.

One at a time: for...of

A for...of loop is ordinary code inside cleanUp. An await in its body pauses cleanUp itself.

function deleteLoan(id) {
  return Promise.resolve().then(() => {
    console.log("deleted loan " + id);
  });
}

async function cleanUp() {
  const ids = [7, 9];
  for (const id of ids) {
    await deleteLoan(id);
  }
  console.log("clean-up finished");
}

cleanUp();
deleted loan 7
deleted loan 9
clean-up finished

Each deletion finishes before the next one starts. Use this when the order matters. Filling a form field by field is one case. A set of steps where each one needs the result of the one before is another.

All together: map and Promise.all

When the pieces of work are independent, start them all and wait once. map turns each id into a promise, and Promise.all waits for the whole array.

function deleteLoan(id) {
  console.log("deleting loan " + id);
  return Promise.resolve().then(() => {
    console.log("deleted loan " + id);
  });
}

async function cleanUp() {
  const ids = [7, 9];
  await Promise.all(ids.map((id) => deleteLoan(id)));
  console.log("clean-up finished");
}

cleanUp();
deleting loan 7
deleting loan 9
deleted loan 7
deleted loan 9
clean-up finished

Both deletions start before either one finishes, and "clean-up finished" still waits for both. With real requests to a server, this takes about as long as the slowest request, where the loop takes the sum of all of them.

map with an async callback has the same trap as forEach when you forget the Promise.all. It gives you an array of promises, and nothing waits for them.

Which one to use

Ask whether one piece of work can affect another.

  • Steps on one page, in a fixed order: for...of with await. A page handles one user at a time.
  • Independent requests, such as creating or deleting test data through an API: map with Promise.all.
  • Not sure: for...of. It is slower and it is never wrong.

The same applies to filter, some and every. They do not wait for an async callback either. A promise counts as true in a condition, so filter with an async callback keeps every item. Do the asynchronous work first with one of the two patterns above, then filter the results.

A reviewer who sees forEach(async in a test will stop reading there. It is nearly always a bug, and it is quick to find by searching for that text.

Remember this

forEach does not wait for an async callback. Use for...of with await when steps must happen in order. Use map with Promise.all when the work is independent.

Reference: for...of on MDN.

now prove it

Reading is the setup. Solve this exercise in the editor. We run your code on each case and compare what it prints with the expected output.