Callback (Node.js)

A callback is a function passed into another function to be called later, typically when an async operation finishes. Node's classic style is the error-first callback: (err, result) => {...}, with the error as the first argument.

Node.js

Callbacks are the original way Node handled asynchrony. You pass a function to an async API, and Node invokes it when the work completes. The convention is error-first: the callback receives an error as its first argument (null if all went well) and the result(s) after it, so you always check err first.

Nesting many dependent callbacks leads to 'callback hell' — deeply indented, hard-to-read code where each step lives inside the previous one's callback. This readability problem is exactly what Promises and async/await were created to solve.

Modern Node code prefers Promises and async/await, but callbacks remain everywhere in older APIs and event handlers. You can wrap a callback-based function into a Promise with util.promisify, or use the fs.promises-style APIs that return Promises directly.

Syntax

doAsync((err, result) => { if (err) ...; });

Examples

JavaScript

const fs = require("fs");

fs.readFile("data.txt", "utf8", (err, data) => {
  if (err) return console.error("failed:", err.message);
  console.log("contents:", data);
});

Learn it in a lesson

See also

Back to the Dictionary