Asynchronous JavaScript

Callbacks

Callbacks are JavaScript's oldest async pattern — functions passed as arguments and called later when an operation completes. Understanding callbacks is essential because Promises and async/await are built on the same concept.

What is a callback in JavaScript?

A callback is a function you pass to another function so it can be called later: when an event happens, when a timer fires, or for each item in an array. button.addEventListener("click", handleClick) and [1, 2].map(n => n * 2) both use callbacks. Deeply nested asynchronous callbacks ("callback hell") are why promises and async/await were introduced.

setTimeout(() => console.log("1 second later"), 1000);
[3, 1, 2].sort((a, b) => a - b);

// Node-style error-first callback
fs.readFile("a.txt", "utf8", (err, data) => {
  if (err) return console.error(err);
  console.log(data);
});

Callback Types

Synchronous

Called immediately within the current execution. Examples: Array.map, Array.filter, Array.sort.

Asynchronous

Called later, after the current call stack is empty. Examples: setTimeout, fetch, fs.readFile.

Event-driven

Called when a specific event fires. Examples: addEventListener, on('data'), on('error').

Error-first (Node.js)

First argument is always an error (or null). Second is the result. Standardises error handling.

Callback vs Promises vs async/await

Error handlingManual, error-prone (must check every err)Centralized .catch()try/catch block
CompositionNested (callback hell)Chained .then()Sequential code
Parallel opsComplex with counterPromise.all()await Promise.all()
CancellationManual flagsAbortControllerAbortController
DebuggingStack traces lose contextBetter but not perfectExcellent — reads like sync
–CallbacksPromisesasync/await

Useful Callback Utilities

once(fn)
function once(fn) {
  let called = false;
  return (...args) => {
    if (called) return;
    called = true;
    return fn(...args);
  };
}
promisify(fn)
function promisify(fn) {
  return (...args) => new Promise((res, rej) => {
    fn(...args, (err, result) =>
      err ? rej(err) : res(result)
    );
  });
}
debounce(fn, ms)
function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), ms);
  };
}
after(n, fn)
function after(n, fn) {
  let count = 0;
  return (...args) => {
    if (++count === n) fn(...args);
  };
}
// Run fn only after 3 callbacks complete

Common Pitfalls

Not returning after calling the error callback — code continues after error path
Always use 'return cb(err)' or an if/else to prevent double-invocation of the callback
Calling the callback synchronously in some cases and asynchronously in others — unpredictable
Be consistently async. Wrap sync code in process.nextTick / setTimeout(fn, 0) if needed
Deeply nested callbacks (callback hell) — unreadable, hard to debug and maintain
Use named functions, promisify, or refactor to Promises / async-await
Forgetting to handle errors — unhandled errors silently break the app
Always check the err argument first. Use a centralized error handler if errors repeat.

Interactive Callback Demo

Code Editor

<button id="go">Run</button>
<ol id="out"></ol>

Preview

Callbacks — step by step

1 / 4
1

What is a callback function

A callback is a function passed as an argument to another function, to be invoked at a later time — after an asynchronous operation completes or when a specific event occurs. Callbacks are the foundation of JavaScript's async model: setTimeout, addEventListener, array methods like map/filter all use them.

1 of 4
🔍Callbacks are still everywhere
Despite Promises and async/await, callbacks remain essential. Array methods (map, filter, reduce, forEach, sort), event listeners, setTimeout/setInterval, and many Node.js core APIs all use callbacks. Understanding callbacks deeply makes it easier to understand how Promises and async/await work under the hood.

🎯 Quick Check

What is the main problem with deeply nested callbacks?

JavaScript Callbacks: summary

Key points

  • Synchronous callbacks run immediately (map, forEach); asynchronous ones run later (setTimeout, events).
  • Error-first callbacks take (err, result), a Node.js convention.
  • Convert callback APIs to promises with util.promisify or by wrapping them in new Promise.

Frequently asked questions

›What is callback hell?

Several asynchronous steps nested inside each other's callbacks, which makes code drift right and become hard to follow. Promises and async/await flatten it.