How to use callbacks in Node.js

· Category: Node.js

Short answer

A callback is a function passed as an argument to an asynchronous function that is executed once the operation completes. Node.js follows the error-first convention.

Steps

  1. Define a function that accepts a callback: function readData(callback) { ... }.
  2. Invoke the callback on success: callback(null, result);.
  3. Invoke the callback on error: callback(new Error('Failed'));.
  4. Call the function: readData((err, result) => { if (err) { ... } else { ... } });.
  5. Avoid deeply nested callbacks by extracting named functions or using promises.

Tips

  • Always check for errors first in your callback implementation.
  • The error-first pattern (err, data) is a universal convention in the Node.js ecosystem.

Common issues

  • Deeply nested callbacks lead to callback hell and make code hard to read.
  • Forgetting to return after calling callback(err) may cause double invocations.