agyanadda@gmail.com

Node.js Callbacks

Asynchronous Programming 1 min read Updated Dec 3, 2026 Topic 12 of 30

A callback is a function passed to another function, to be called when work is finished.

Error-first callbacks

Node's classic APIs call your function with the error first: (err, result) => {}. Always check err before using result.

Callback hell

When each step depends on the previous one, callbacks nest deeper and deeper (the "pyramid of doom"). The code becomes hard to read and error handling repeats everywhere.

The solution: Promises

  • Most Node APIs have a promise version (node:fs/promises)
  • util.promisify(fn) converts an error-first callback function into one that returns a promise
  • Then use async/await (next lesson)

You will still see callbacks in event listeners (server.on('request', cb)), array methods (map, filter) and older libraries.

Example

Example — From callback hell to async/await JavaScript
import fs from 'node:fs';
import { promisify } from 'node:util';

// ❌ Callback style: nested and repetitive
fs.readFile('a.txt', 'utf8', (err, a) => {
  if (err) return console.error(err.message);
  fs.readFile('b.txt', 'utf8', (err, b) => {
    if (err) return console.error(err.message);
    fs.writeFile('ab.txt', a + b, (err) => {
      if (err) return console.error(err.message);
      console.log('Merged (callbacks)');
    });
  });
});

// ✅ Same task with promisify + async/await
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

try {
  const a = await readFile('a.txt', 'utf8');
  const b = await readFile('b.txt', 'utf8');
  await writeFile('ab.txt', a + b);
  console.log('Merged (async/await)');
} catch (err) {
  console.error(err.message);
}

Both versions merge a.txt and b.txt into ab.txt. The async/await version is flat and has one place for error handling.

Test Yourself With Exercises

Exercise 1 Multiple Choice

In an error-first callback, what is the first argument?

Exercise 2 True / False

util.promisify converts an error-first callback function into a promise-returning function.

Exercise 3 Fill in the Blank

Deeply nested callbacks are called callback ___.

Frequently Asked Questions

No. Callbacks are a normal part of JavaScript (event listeners, array methods). Only deeply nested async callbacks are a problem, and promises with async/await solve that.