In this lesson, you added one box to the event loop picture, the microtask queue, and used it to explain why a .then() handler on a promise that’s already fulfilled runs before a timer that was set first.
Key Points
- In the picture you know, your code runs on the call stack, a timer waits in the waiting area, its callback joins the task queue when it’s due, and the event loop moves one task across when the stack is empty.
- In
museum_order.mjs, the timer is set first with a delay of zero, yet the handler onkioskReady, a promise already fulfilled throughPromise.resolve(), logs before it. Node waits at least one millisecond even for a delay of zero, so the run alone doesn’t say whether the handler was ready first or gets priority. - Node keeps a second queue, the microtask queue. A promise’s handler joins it once its promise is fulfilled, never the task queue. A handler on a promise that’s already fulfilled has nothing to wait for, so it goes straight into the microtask queue.
- When the stack is empty, the event loop checks the microtask queue before it moves a task. It runs every microtask, one after another, until that queue is empty. Only then does it move the next task, even if a timer’s callback is already due and waiting in the task queue.
- At an
await, the async function always steps aside, even when the promise it awaits is already fulfilled. When that promise is fulfilled, the rest of the function joins the microtask queue. IngreetFamily(), that’s straight away, so it joins behind the handler that was queued first.
The rule is that whenever the call stack is empty, the event loop runs every microtask, then moves the next task. Promise handlers and the code after an await are microtasks. Timer callbacks are tasks. So a timer that’s set first can still run last.