Loading video player…

Promises Run Before the Next Timer

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:

Language: Python
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:

Language: JavaScript
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:

Language: Program Output
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:

Language: JavaScript
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:

Language: Program Output
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:

Language: JavaScript
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:

Language: Program Output
[ '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:

Language: JavaScript
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:

Language: Program Output
[ '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.

00:00 In this lesson, you’ll 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.

00:21 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.

00:31 asyncio’s ready queue is first in, first out, so once main() yields, the log shows start, end, timer, promise.

00:42 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.

00:53 Promise.resolve() hands back a promise that’s already fulfilled, the finished future, and .then() registers the handler. In what order do the four labels print?

01:03 Your turn: pause the video and predict.

01:12 Start and end come first, but then promise prints before timer.

01:19 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.

01:38 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.

01:48 .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.

01:59 With the stack empty, JavaScript runs a microtask checkpoint before anything else. It runs the microtasks in order until the queue is empty: promise. Only then does the event loop take the next task, the timer callback, which logs timer.

02:17 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.

02:29 queueMicrotask() takes a callback and adds it to the microtask queue directly, no promise needed. The log shows the new label between promise and timer.

02:39 Microtasks run in the order queued, all before the timer. Like asyncio’s call_soon(), queueMicrotask() runs a callback right after the current code.

02:52 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 jumps ahead of every waiting timer.

03:05 So use queueMicrotask() when code must run before anything else waiting, and a zero-delay timer when waiting work should go first.

03:16 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.

03:30 The log shows four labels: timer is missing. 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.

03:49 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.

04:03 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().

04:14 The timer callback records timer, then calls resolve(), and await timer pauses ordering() until then.

04:21 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.

04:31 The log shows all five labels, the dashboard’s reference order.

04:37 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.

04:51 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.

Become a Member to join the conversation.