Skip to article content
FrontendXLesson 07 / 20

Async bugs: missing awaits, races and ordering

Turn a vague failure report into a reproduction, isolate the cause, form and falsify hypotheses, instrument the code, fix async and state bugs, lock the fix behind a regression test and review changes for real trade-offs.

intermediate · about 45 minutes · 2 exercises

  • Predict
  • Debug

What you will be able to do

#
  • Find a missing await that lets a function return too early.
  • Guard against a stale response overwriting a newer one.
  • Predict the order of synchronous code, microtasks and timers.

Overview

#

Async bugs are ordering bugs. The code is correct line by line, but the lines do not run in the order you assumed.

The first trap is the missing await. A promise that is not awaited runs later, and its rejection may become an unhandled rejection instead of a caught error.

snippet.js
async function saveAll(docs) {
  docs.forEach((doc) => {
    save(doc); // not awaited
  });
  return 'done';
}

This returns done before any save completes. Use a for-of loop with await, or Promise.all when the saves are independent.

snippet.js
async function saveAll(docs) {
  await Promise.all(docs.map((doc) => save(doc)));
  return 'done';
}

The second trap is the race. Two requests start, and the slower one finishes last and overwrites the newer result.

snippet.js
async function load(query) {
  const res = await fetch(`/search?q=${query}`);
  setResults(await res.json());
}

If the user types again before the first response arrives, an older response can land after a newer one. Guard with a request token or cancel the previous request.

snippet.js
let latest = 0;
async function load(query) {
  const token = ++latest;
  const res = await fetch(`/search?q=${query}`);
  const data = await res.json();
  if (token === latest) setResults(data);
}

The third trap is microtask versus timer ordering. Promise callbacks run before setTimeout callbacks scheduled at the same time, because microtasks drain before the next macrotask. Predict the order before you run it.

When an async bug appears, write down the intended order and the actual order. The difference names the bug.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Debug

    saveAll returns done before any document is saved because the promises are not awaited. Fix it so it resolves only after every save completes, and rejects if any save fails.

    starter.javascript
    async function saveAll(docs) {
      docs.forEach((doc) => {
        save(doc);
      });
      return 'done';
    }

    Reveal the reference answer
    reference.javascript
    async function saveAll(docs) {
      await Promise.all(docs.map((doc) => save(doc)));
      return 'done';
    }

    Authored expected output: The returned promise resolves after all saves settle; if one save rejects, the returned promise rejects.

    forEach ignores the promise each save returns, so the function returns immediately. Promise.all collects the promises and settles when all of them do, and rejects on the first failure.

  2. Exercise 2Predict

    In what order are these lines logged?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    console.log('1');
    setTimeout(() => console.log('2'), 0);
    Promise.resolve().then(() => console.log('3'));
    console.log('4');
    Choose the best answer

Common misconceptions

#
  • Calling an async function inside forEach waits for each call.
  • The last response to arrive is always the newest request.

Follow-up practice

#
  • debugging-review-08-regression-tests

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.