Error-first callbacks and promisify

Beginner · 6 min

Node's (err, data) callback convention, why it exists, how util.promisify and callbackify bridge to promises, and when to use fs/promises instead.

Before thisThe event loop phasesThe util module

Codevolution · 6 min

Error-first callbacks and promisify

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Node's callback convention is error-first: the callback's first argument is an `Error` or `null`, and results follow. Always check the first argument before using the rest.
  • A callback must be called either always synchronously or always asynchronously. Mixing the two makes code behave differently depending on cached state, a bug often called releasing Zalgo.
  • `util.promisify(fn)` wraps an error-first function so it returns a promise: a non-null first argument rejects, otherwise the second argument resolves.
  • Many core APIs already ship promise versions: `node:fs/promises`, `node:timers/promises`, `node:stream/promises`, `node:dns/promises`. Use those directly and promisify only what has none.
  • A few functions customise promisify: `util.promisify(execFile)` resolves to `{ stdout, stderr }`, and `util.promisify(setTimeout)` takes the delay first and resolves with a value.

Where the convention comes from

Before promises existed in JavaScript, Node needed a uniform way for asynchronous functions to report results. The rule the core team settled on is simple: the callback is the last argument, and its first argument is the error.

import fs from 'node:fs';

fs.readFile('d.txt', 'utf8', (err, data) => {
  if (err) return console.error(err.code); // handle first, then return
  console.log(data);
});

On success err is null. On failure it is an Error and the remaining arguments are undefined. Because every API follows the shape, you can learn it once. And because the error comes first, forgetting to check it is a visible gap in the code, not a missing optional argument at the end.

Why not throw? A try/catch around a call only catches what happens during that call. By the time an asynchronous operation fails, the call stack that started it is gone, so there is nothing to catch into. The error has to be passed forward as a value. Promises solved this by building the same idea into the language, as the JavaScript lessons explain.

The one rule: never mix sync and async

A function that takes a callback must call it consistently: always synchronously, or always asynchronously. This breaks the rule:

function get(key, cb) {
  if (cache.has(key)) return cb(null, cache.get(key)); // sync
  setTimeout(() => cb(null, load(key)), 1);            // async
}

I ran a version of it: with a cached value the callback printed before the line after the call; with a miss it would print after. Code that depends on ordering then works in testing, where the cache is cold, and fails in production, where it is warm. The fix is to make the fast path asynchronous too: process.nextTick(cb, null, value). Better, return a promise, which guarantees asynchronous resolution.

Bridging with promisify

util.promisify turns an error-first function into one that returns a promise:

import fs from 'node:fs';
import { promisify } from 'node:util';

const readFile = promisify(fs.readFile);
console.log(await readFile('d.txt', 'utf8')); // hi

function addLater(a, b, cb) {
  setTimeout(() => {
    if (typeof a !== 'number') return cb(new TypeError('a must be number'));
    cb(null, a + b);
  }, 5);
}
const addP = promisify(addLater);
console.log(await addP(1, 2)); // 3
await addP('x', 2).catch((e) => console.log(e.message)); // a must be number

A non-null first argument rejects; otherwise the second argument resolves. Only the second: if a function calls back with several values, you get the first. Some core functions define their own promisified form to deal with that, and those override the generic behaviour. promisify(execFile) resolves with { stdout, stderr }, and promisify(setTimeout)(5, 'val') takes the delay first and resolves with 'val'.

The reverse, util.callbackify(asyncFn), exists for the rare case where an old API insists on callbacks.

Prefer the built-in promise APIs

Most of what you would promisify already has a promise twin: node:fs/promises, node:timers/promises (setTimeout as sleep), node:stream/promises, node:dns/promises, and promise methods on fs.promises. Use those directly:

import { readFile } from 'node:fs/promises';
import { setTimeout as sleep } from 'node:timers/promises';

const text = await readFile('d.txt', 'utf8');
await sleep(100);

Reach for promisify for third-party or legacy callbacks and for core functions with no promise version. For your own new code, write functions that return promises and skip the callback form.

What the video covers

Codevolution’s “Callback Pattern” is episode 20 of Vishwas Gopinath’s Node.js tutorial, a short beginner-level introduction. By title and length it covers what a callback is and how Node uses them. It may not reach util.promisify, so the sync/async rule, promisify, callbackify and the built-in promise modules above are carried by this page. Angular University’s five-minute video under “go deeper” covers promisify directly, but dates from 2017, before fs/promises was standard. I could not read a transcript of either.

Where this fits

Callbacks are the substrate; most new code starts at async/await in JavaScript. Once your operations return promises, the next question is stopping them early: cancellation with AbortController. Both rely on the event loop to run the callbacks.

Check yourself

  1. 01What are the two things Node's callback convention fixes about callback signatures?

    The callback is the last argument, and its first parameter is reserved for the error, `null` or `undefined` on success. Every function follows the same shape, so error handling can be written the same way everywhere and one helper like `promisify` can wrap them all.

  2. 02Why is `if (cached) return cb(null, value)` followed by an asynchronous path a problem?

    Callers cannot predict ordering. With a cached value the callback runs before the function returns, so code after the call has not run yet. With a cache miss it runs later. Make both paths asynchronous with `process.nextTick(cb, null, value)` or `queueMicrotask`, or switch to returning a promise.

  3. 03A callback API passes three results: `cb(err, a, b)`. What does `promisify` resolve with?

    Only the first result, `a`, unless the function defines `util.promisify.custom`. To receive several values, wrap it by hand in a promise that resolves with an object, or have the function itself return a promise.

  4. 04What does `util.callbackify` do and when is it useful?

    It converts a function that returns a promise into one that takes an error-first callback. It helps when you must hand an async function to an older API that only accepts callbacks.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark