What does this code print, and in what order?
The output is one, six, four, three, five, two. Working through why is the whole point of the exercise.
console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
(async () => {
console.log("4");
await null;
console.log("5");
})();
console.log("6");The synchronous pass comes first and prints one, four and six. The async function body runs synchronously up to its first await, so four is printed during that pass, in the middle. The await then suspends the function and schedules its continuation.
Next comes the microtask queue. The promise callback for three was registered before the async function even ran, so it is ahead in the queue, and the continuation of the async function is behind it. So three prints, then the continuation runs and prints five.
Finally the timer task runs and prints two. A timer with a zero delay still waits until the current task and the whole microtask queue are finished.
Three rules explain the whole thing. Synchronous code runs in order. The microtask queue is drained completely before the next macrotask. And an await is a microtask, so it never runs before the promise callbacks that were queued ahead of it.