Asynchronous result callbacks
How it works
A callback is a function supplied to another operation. It can run synchronously or be scheduled by the host. A common Node-style convention passes an error first and a result second; the callback should handle one outcome and return rather than continuing into the success path. A return inside a later callback does not return from the original outer function. Use a callback contract that documents when and how often it runs.
Example 1
function read(done) { queueMicrotask(() => done(null, 8)); }read((err, value) => console.log(err ? "error" : value));console.log("started");Expected output in the tested environment:
started8The microtask runs after the current synchronous code.
Example 2
function read(done) { queueMicrotask(() => done(new Error("missing"))); }read((err, value) => { if (err) { console.log(err.message); return; } console.log(value); });Expected output in the tested environment:
missingAn early return skips the success path.
Common mistake
Not all callbacks are asynchronous: Array.map invokes its callback during the call.
Practice
Adapt the example to return a simulated error for an invalid identifier; ensure exactly one callback invocation.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Asynchronous result callbacks — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
Does accepting a callback make a function inherently asynchronous?
What should an error-first callback usually do after handling an error?
Why cannot a later callback return the outer call’s original return value?
For Asynchronous result callbacks, what is the console output of example 1 in Node.js 22.16.0?
function read(done) { queueMicrotask(() => done(null, 8)); }read((err, value) => console.log(err ? "error" : value));console.log("started");For Asynchronous result callbacks, what is the console output of example 2 in Node.js 22.16.0?
function read(done) { queueMicrotask(() => done(new Error("missing"))); }read((err, value) => { if (err) { console.log(err.message); return; } console.log(value); });