Skip to content

L11 Callbacks and async order

20 minSuggested first: L10 Call chains and trace boundaries

Outcome

Distinguish registering a callback from invoking it, and predict the order around an awaited promise.

Learn

A callback is a function you pass for someone else to call. Passing it as a value doesn't call it.

In JavaScript, an async function runs synchronously until it first suspends at an await; the code after the await resumes later. When reading a trace, keep three orders apart: the order things are registered, the order they're invoked, and the order they finish.

Worked example

The promise on line 4 fulfills. In what order are A, B and C pushed?

JavaScript
const events = [];
async function work() {
  events.push("A");
  await Promise.resolve();
  events.push("B");
}
void work();
events.push("C");
Predict first, then show the worked explanation

Calling work on line 7 pushes A, then pauses at await. Control returns to the caller, which pushes C on line 8. Only then does the continuation resume and push B. The order is A, C, B.

Practice and check

Guided practice

Practice, not scored

Given const callback = () => events.push("X");, which event does that declaration alone append?

Choose one answer

Exit check

Counts toward completion

Move events.push("C") so it runs before void work(). What's the order now?

Choose one answer

Common mistake

Assuming an already-resolved promise lets await skip suspending. Mark the continuation separately from the synchronous statements.

Practice on a real repository

Try the puzzle below once you can tell a function passed as a value from the function running. Streams and subscriptions come back in L21.

Practice is optional. Solving a puzzle doesn't complete a lesson, and lessons never change a puzzle's points.

References