Promises Run Before the Next Timer
In this lesson, you port an asyncio refresh routine and find out whether JavaScript runs its
callbacks in the same order. The station dashboard’s refresh routine logs start and end, and in between it schedules two
callbacks: a redraw, labeled timer, and a handler for a cached reading, labeled promise.
In Python’s asyncio, call_soon() schedules the redraw to run next, with no delay at all, and the
finished future’s done callback comes second:
import asyncio
async def main():
loop = asyncio.get_running_loop()
print("start")
loop.call_soon(print, "timer")
reading = loop.create_future()
reading.set_result(None)
reading.add_done_callback(lambda _: print("promise"))
print("end")
await asyncio.sleep(0)
asyncio.run(main())
asyncio’s ready queue is first in, first out, so once main() yields, this prints start, end, timer and
promise, one per line.
In the JavaScript port, the redraw becomes a timer with a zero delay. A timer callback never interrupts
running code, so it waits for the module to finish. Promise.resolve() hands back a promise
that’s already fulfilled, the finished future, and .then() registers the handler:
console.log("start");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("end");
start and end come first, but then promise prints before timer:
start
end
promise
timer
In asyncio, every callback that’s ready to run, call_soon() callbacks and done callbacks alike, waits
in one ready queue. JavaScript splits waiting work into two kinds of queue: a task queue for timer callbacks, and a microtask queue for promise jobs.
From the top, the module logs start. setTimeout() hands its callback to a timer, and once
the delay is up, the callback waits in the task queue. .then() on a fulfilled promise queues its
handler as a promise job in the microtask queue. Then the module logs end, and its code is done.
With the stack empty, JavaScript runs a microtask checkpoint before anything else. It runs the
microtasks in order until the queue is empty, which logs promise. Only then does the event loop take
the next task, the timer callback, which logs timer.
After every task, the stack empties and another checkpoint runs. So the order you schedule things in doesn’t decide it: the microtask queue always empties first.
queueMicrotask() takes a callback and adds it to the microtask queue directly, no promise
needed. The dashboard queues one more label after the promise’s:
console.log("start");
setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("promise"));
queueMicrotask(() => console.log("microtask"));
console.log("end");
The log shows the new label between promise and timer. Microtasks run in the order queued, all
before the timer:
start
end
promise
microtask
timer
Like asyncio’s call_soon(), queueMicrotask() runs a callback right after the current code. The
analogy stops at who shares the line: asyncio’s ready queue also takes timers that have come due, so
a due timer can run between call_soon() callbacks, while a microtask goes ahead of every waiting timer. So
use queueMicrotask() when code must run before anything else waiting, and a zero-delay timer when
waiting work should go first.
To check the order, the dashboard’s helper ordering() collects the labels in a
trace, and first returns it right away. .push() is JavaScript’s append(), and the module awaits
the async function’s promise and logs the trace:
async function ordering() {
const trace = ["start"];
setTimeout(() => trace.push("timer"), 0);
Promise.resolve().then(() => trace.push("promise"));
queueMicrotask(() => trace.push("microtask"));
trace.push("end");
return trace;
}
console.log(await ordering());
The log shows four labels, and timer is missing:
[ 'start', 'end', 'promise', 'microtask' ]
Why did promise and microtask make it? The await queues the rest of the module, the logging, as
a promise job. It joins the microtask queue behind the other two, so it runs at
the same checkpoint, before the timer. JavaScript’s await always queues the rest as a promise job,
even when the promise is already fulfilled. In Python, awaiting a coroutine that returns without
pausing doesn’t go through the loop at all.
To wait for the timer, ordering() wraps it in a promise. new Promise() runs the function you pass
it right away and hands it resolve, the promise’s set_result(). The timer
callback records timer, then calls resolve(), and await timer pauses ordering() until
then:
async function ordering() {
const trace = ["start"];
const timer = new Promise((resolve) => {
setTimeout(() => {
trace.push("timer");
resolve();
}, 0);
});
Promise.resolve().then(() => trace.push("promise"));
queueMicrotask(() => trace.push("microtask"));
trace.push("end");
await timer;
return trace;
}
console.log(await ordering());
This time, the timer callback’s resolve() queues the rest of ordering() as a promise job, which the
next checkpoint runs: ordering() returns the trace. The log shows all five labels, the dashboard’s reference order:
[ 'start', 'end', 'promise', 'microtask', 'timer' ]
So whenever the stack empties, JavaScript runs a microtask checkpoint: every promise job and queued
microtask, in order, before the next timer. And an await continuation is a
promise job too.
Next up is the exercise Trace the Station Alert Queue. There, you’ll predict and explain the order of a station alert trace, and fix a report about it.