CodePark/ questions / Event loop
START PRACTICINGPRACTICE
Frontend question · JavaScript › Event loop

What does this log?

async function run() {
  console.log("a1");
  await null;
  console.log("a2");
}
console.log("s");
setTimeout(() => console.log("t"), 0);
run();
Promise.resolve().then(() => console.log("p"));
console.log("e");
s a1 e a2 p t

The answer is s a1 e a2 p t. Here is the order step by step:
•
s logs. The timer callback goes into the task queue.
•
run() starts. An async function runs synchronously until its first await, so a1 logs.
•
await null pauses run. It puts "resume run" into the microtask queue. This happens on the run() line.
• The next line adds the
then callback to the microtask queue, after "resume run".
•
e logs, and the script ends.
• The microtask queue empties in order: first
a2, then p.
• The timer is a task (macrotask), so it waits until all microtasks are done.
t logs last.

The tempting option "s a1 e p a2 t" is wrong because "resume
run" was queued before the then callback.