Node.js Developer interview question · Most asked

How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?

Summary

Node started with error-first callbacks ((err, data) => {}), moved to Promises (chainable, composable) and now favors async/await on top of Promises, with promise-based core APIs like fs/promises, timers/promises and stream/promises.

Longer Answer

Callbacks led to deeply nested 'callback hell' and inconsistent error handling. Promises allow Promise.all, allSettled, race and any for composition, and async/await makes async code read sequentially with try/catch. util.promisify converts callback APIs. Always handle rejections; unhandled rejections crash the process by default since Node 15.

Code Example

import { readFile } from "node:fs/promises";

async function loadConfigs(paths) {
  const results = await Promise.allSettled(paths.map((p) => readFile(p, "utf8")));
  return results
    .filter((r) => r.status === "fulfilled")
    .map((r) => JSON.parse(r.value));
}

Key Points

  • Error-first callbacks (legacy)
  • Promises for composition
  • async/await with try/catch
  • Promise-based core modules
  • Unhandled rejections crash the process

More most-asked Node.js Developer questions

← All Node.js Developer questions