Skip to the page

Output prediction drills · core

Predicting async output: a method

To predict any event-loop puzzle, label every line as sync, microtask or task; run all sync code first; then drain microtasks in the order they were queued (a chained .then is queued only when the previous step finishes); then take one task at a time and drain microtasks again after each.

The notes

What you must know

  • Step 1: sync lines in order. This includes promise executors and async function bodies up to their first await.
  • Step 2: write the microtask queue down. When a promise settles, append its handlers. Keep going until it is empty.
  • Step 3: tasks in order of due time (setTimeout delay; equal delays run in creation order). After each task, drain microtasks before the next task.
  • Rules to remember: an await continuation is a microtask; returning a promise from then or an async function costs 2 extra ticks; finally adds ticks; in Node, process.nextTick runs before promises.
  • Talk while solving. Interviewers grade the explanation, not only the final order.

The red pen

Common traps: mistake → fix

  • Mistake: Queuing all .then calls of a chain at once

    Fix: each is queued only when the previous step finishes.

  • Mistake: setTimeout(fn, 0) beats an already-resolved promise

    Fix: never.

  • Mistake: Forgetting that the executor and the code before the first await are synchronous.

Easy to hard

Questions interviewers ask, easy to hard

  1. Warm-up: a resolved promise vs setTimeout 0.
  2. The classic async1/async2 ordering.
  3. Timers that schedule promises that schedule timers.
  4. Mixed queueMicrotask, await null and then-chains.
  5. Returning a promise from then: where does the next step land?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview