Async & Microtask Debugging

JavaScript has only one line of work, so code takes turns. The event loop (the rule for those turns) runs the sync code (ordinary code, line by line) to the…

The Save button says "Saved", but the data never reaches the database. When you click, the Console is clean. The error only appears almost a second later, and it doesn't point to any line you suspect.

That's the mark of an async bug: code doesn't run when you think it does. The result isn't there yet when you use it, nobody catches the error, or the order differs from the order of the lines you wrote. To understand an async bug, you need to know how JavaScript takes turns. JavaScript has only one line of work (a thread), like a single cashier in a small shop. The cashier finishes the customer being served before anything else. Anything marked "later" goes into one of two queues: an express queue for small jobs that must be done right away, and the regular queue. Every time one customer is done, the cashier empties the express queue first, then calls one person from the regular queue.

The order: sync, microtask, macrotask

This is what each part of the cashier picture stands for:

This code prints five letters, from those three kinds of turn:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");

Before you look at the table below, guess: in what order do these five letters print?

Step What runs Printed Microtask queue Macrotask queue
1 console.log("A") A empty empty
2 setTimeout(...) empty B
3 Promise.resolve().then(...) C B
4 queueMicrotask(...) C, D B
5 console.log("E") E C, D B
6 sync code done, empty the microtasks C, D empty B
7 take one macrotask B empty empty

The result is A, E, C, D, B, which is often not the first guess. setTimeout(fn, 0) doesn't mean "right now", it means "after the sync code and every microtask are done".

Bug 1: a missing await

await means "wait until this Promise is done, then go on to the next line". Without await, the function keeps running, and the Promise is left running on its own with nobody waiting for it. A Promise that nobody waits for is called a floating promise. The code below holds the fake database from this page's Lab. This fake database answers 800 ms later, and while the "Database fails" switch is on, its answer is an error. This code shows only the failing version.

const db = {
  insert(order) {
    return new Promise((resolve, reject) => {
      setTimeout(() => reject(new Error("DB down")), 800); // fails after 800 ms
    });
  },
};

async function saveOrder(order) {
  db.insert(order); // missing await
  return { status: "saved" };
}

async function saveOrderFixed(order) {
  await db.insert(order); // wait until the insert is done
  return { status: "saved" };
}

This table compares the two functions over time. The UI is what the user sees on the screen:

Time saveOrder (missing await) saveOrderFixed
0 ms returns { status: "saved" } right away, the UI says "Saved" stops at await and waits
800 ms the insert fails, nobody is waiting: Uncaught (in promise) Error: DB down await throws Error: DB down to its caller

Bug 2: an unhandled rejection

A Promise that fails is called rejected. If there is no .catch() or try/catch to catch it, it's an unhandled rejection (a failure that nobody handles). The browser prints Uncaught (in promise) Error: DB down in the Console, and the user gets no message at all. In Node.js 15 and later, an unhandled rejection even stops the program.

This is how to catch it, with try/catch around the await. show writes a message on the screen:

async function handleSave(order) {
  try {
    await saveOrderFixed(order);
    show("Saved");
  } catch (err) {
    show("Could not save: " + err.message); // Could not save: DB down
  }
}

Checking all three in the exercise

The exercise models the three things above (the order of turns, a missing await, an unhandled rejection) with plain data. In simulateEventLoop, the event loop becomes three filter calls. In detectUnhandledRejection, each Promise has a chained property: false means nothing catches it.

function simulateEventLoop(tasks) {
  const sync = tasks.filter((t) => t.type === "sync").map((t) => t.label);
  const micro = tasks.filter((t) => t.type === "micro").map((t) => t.label);
  const macro = tasks.filter((t) => t.type === "macro").map((t) => t.label);
  return [...sync, ...micro, ...macro];
}

function detectUnhandledRejection(promises) {
  return promises.filter((p) => !p.chained).map((p) => p.id);
}

findForgottenAwait reads code as text, line by line, with a rough rule: a line that calls a function and ends with ;, but contains none of the words await, return or function, is suspected of a missing await.

Line Its content Reported? Why
1 async function save(order) { no has the word function
2 db.insert(order); yes calls a function without await
3 const data = await fetchUser(); no has await
4 return { status: 'ok' }; no has return
5 } no calls nothing
6 saveOrder(o); yes calls a function without await

So the exercise's three output lines are A,E,C,D,B, then 2,6, then p2,p3 (p2 and p3 are the ones whose chained is false). This text rule is only for practice: it would also suspect console.log("x");. A real tool like that ESLint rule uses the data types from TypeScript (JavaScript with added notes about data types), so it knows what is really a Promise.

💡 Async stack traces in DevTools

When an error is thrown inside an async function, its stack trace still lists the function that was waiting for it with await. In err.stack (the error's stack trace as text) you'll find a line like at async handleSave (app.js:3:5), which points at await saveOrderFixed(order). The exception is an error created in a setTimeout callback, like the fake database's DB down error: its stack trace stops at that callback. The Call Stack in Chrome DevTools is different: DevTools joins the Call Stack across await and setTimeout automatically. So when you stop at a breakpoint inside a callback, you can still see the function that scheduled it. Add console.trace("label") to print the stack trace without stopping.

⚠️ Why the order is off and the error slips through

TL;DR: JavaScript has only one line of work, so code takes turns. The event loop (the rule for those turns) runs the sync code (ordinary code, line by line) to the end, then every microtask (.then, await, queueMicrotask), then one macrotask (setTimeout, events). So code that prints A, B (through setTimeout), C (through .then), D (through queueMicrotask), then E gives A, E, C, D, B. A missing await makes a function return before its work is done. If a Promise nobody waits for (a floating promise) fails, the failure becomes an unhandled rejection (nobody catches it): Uncaught (in promise) Error: .... Catch it with try/catch around the await, or .catch() at the end of a .then chain, and remember that try/catch doesn't help a Promise that isn't awaited.

⚡ Sync, microtask, macrotask

Write:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
queueMicrotask(() => console.log("D"));
console.log("E");
Guess first: ordinary (sync) code runs first, to the end. Then the .then and queueMicrotask callbacks (functions that run later, microtasks), then the setTimeout callback (a macrotask). In what order do these five letters print?

A, E, C, D, B. The sync code runs to the end first (A, E), then every microtask (C, D), then one macrotask (B).

Meaning: setTimeout(fn, 0) doesn't mean "right now", it means "after the sync code and every microtask are done".

⚡ A missing await

Write:

async function saveOrder(order) {
  db.insert(order); // missing await
  return { status: "saved" };
}
Guess first: db.insert saves data to the database, and here the insert fails 800 ms later. The UI (what the user sees) shows "Saved" when this function returns status: "saved". What does it show?

"Saved". The function returns right away, before the insert is done, then 800 ms later Uncaught (in promise) Error: DB down appears.

Meaning: The fix is await db.insert(order): it holds the function on that line until the Promise from db.insert is done. If it fails, await throws its error on that very line.

⚡ Catch the rejection

Meaning: A Promise that fails is called rejected. If there is no .catch() or try/catch to catch it, the failure becomes an unhandled rejection. Put try/catch around the await, or .catch() at the end of a .then chain. But try/catch doesn't help a Promise that isn't awaited: its error appears after the try has finished.

What you will learn