Error-first callbacks
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Trace both callback outcomes
function readQuantity(value, done) { queueMicrotask(() => { if (!Number.isInteger(value) || value < 0) return done(new Error('Invalid quantity')); done(null, value); });}readQuantity(3, (err, value) => console.log(err ? err.message : value));readQuantity(-1, (err, value) => console.log(err ? err.message : value));console.log('scheduled');Run:
node main.mjsExpected stdout:
scheduled3Invalid quantityExit status: 0. Expected stderr: empty.
How it works
A callback is a function supplied to another function. An asynchronous API can call it after the initiating function returns. Check the first argument before using the result: if (err) { ...; return; }. A callback is not automatically asynchronous: the API contract determines when it runs. util.promisify adapts conventional final-argument error-first callbacks to promises; it is not appropriate for arbitrary event listeners. The examples use a microtask to model delayed completion and then the actual file API.
Adapt a callback-based file read
import { readFile } from 'node:fs';import { promisify } from 'node:util';const read = promisify(readFile);console.log(await read('stock.txt', 'utf8'));try { await read('missing.txt', 'utf8'); } catch (err) { console.log(err.code); }Run:
node main.mjsExpected stdout:
booksENOENTExit status: 0. Expected stderr: empty.
Common mistake
Do not expect a try/catch around the call that starts asynchronous work to catch an error thrown later inside a callback. Handle the error where the callback receives it. When implementing a one-shot operation, return after delivering the error so success is not also reported.
Practice
Change the synthetic quantity to 0 and predict both callback branches. Then replace the fixture filename with a missing name and explain ENOENT.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Error-first callbacks — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What is the first argument on successful completion?
Why does the first example print scheduled first?
Which function adapts a conventional error-first callback API?