Interview Hub
Sign in

Q29: How to avoid Callback Hell in Node.js?

MidNode.js 29

Answer

Nested callbacks make code hard to read and to reason about errors. Interviewers want to hear concrete strategies: flatten with named functions, use Promises with .then() chains, or prefer async/await with try/catch. For generator-based flows, libraries historically wrapped yield with thunk runners — today async/await is the default answer.

  • Use async/await Sequential async steps read top-to-bottom. Wrap callback APIs with util.promisify or manual new Promise so you can await them.
  • Promise chains with .then() Each step returns a Promise; attach .catch() once at the end of the chain for a single error sink.
  • Split into small named functions Avoid anonymous inline callbacks five levels deep — export function loadUser(id, cb) style units and compose them.
  • Control-flow utilities async/for await, Promise.all / allSettled, or tiny modules like async (series/waterfall) when you need patterns beyond raw callbacks.
const fs = require("fs").promises;

async function readConfig(path) {
  try {
    const raw = await fs.readFile(path, "utf8");
    return JSON.parse(raw);
  } catch (err) {
    console.error("config failed", err);
    throw err;
  }
}
EditorJavaScript · local only