What does this code print, and in what order?
The code prints one, six, four, three, five, and then two. Working out why it prints them in that order is the whole point of this exercise, so let us walk through it carefully.
console.log("1");
setTimeout(function () {
console.log("2");
}, 0);
Promise.resolve().then(function () {
console.log("3");
});
(async () => {
console.log("4");
await null;
console.log("5");
})();
console.log("6");The first pass runs the synchronous code, and it prints one, four, and six. The async function is worth pausing on here, because its body runs like ordinary synchronous code until it reaches the first await. That means four is printed during this first pass, right in the middle of the other work. The await then pauses the function and schedules its continuation to run later.
Next comes the microtask queue. The promise callback that prints three was registered before the async function even started, so it sits in front of the continuation of that function. So three prints first, and then the continuation runs and prints five.
Finally the timer task runs and prints two. A timer with a delay of zero still has to wait until the current task is finished and the whole microtask queue has been emptied.
Three rules explain the whole thing. Synchronous code runs in the order it is written. The microtask queue is emptied completely before the next macrotask starts. And an await is a microtask, so it never runs before the promise callbacks that were already waiting ahead of it.