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?
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
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.
- How forkJoin recognizes a dictionary of sourcesTrace · Easy · reactivex-rxjs
Practice is optional. Solving a puzzle doesn't complete a lesson, and lessons never change a puzzle's points.
References
- JavaScript Guide (MDN)
- SCIP Code Intelligence Protocol (SCIP maintainers)