Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 156 ยท Asynchronous JavaScript

Asynchronous Callbacks

Learn how asynchronous callbacks work, write error-first callbacks, avoid the pitfalls of callback hell, and see why promises were invented.

Before promises and async/await existed, JavaScript had one way to say "do this when that finishes": pass a function to call later. That function is an asynchronous callback. You have already used them with timers and event listeners, and you'll still meet them every day, in browser APIs, in Node.js and in older libraries.

In this lesson you'll write your own functions that accept callbacks, learn the error-first convention that Node.js made famous, and run into the problems that appear when callbacks get nested deeply: the infamous callback hell. Seeing those problems clearly is the best way to understand why promises were invented.

Synchronous vs asynchronous callbacks

A callback is just a function passed to another function, as you saw in Higher-Order Functions. What matters is when it gets called:

  • A synchronous callback runs right away, before the outer function returns. array.forEach(), map() and sort() work this way.
  • An asynchronous callback runs later, after the outer function has returned, in a future task or microtask. setTimeout(), addEventListener() and many I/O functions work this way.
JS Sync vs async callbacks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The consequence is important: you can't return an asynchronous result. By the time the callback runs, the function that started the work has long since returned. The only way to use the result is inside the callback, or in something the callback calls.

Writing a function that takes a callback

Let's simulate a slow operation, like reading a user record from a server, with setTimeout. The function can't return the user, so it accepts a callback and calls it with the result when it's ready:

JS Delivering results through a callback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

This is exactly how event listeners work, too: addEventListener("click", handler) returns at once, and the browser calls handler later, every time the event happens.

Error-first callbacks

Real operations fail: the network drops, a file is missing, a record doesn't exist. A callback needs a way to receive errors, and try...catch can't help because the error happens later, outside the try block.

Node.js settled on a convention that most callback-based libraries follow: the error-first callback. The callback's first parameter is an error (or null if everything worked), and the result comes second:

JavaScript
callback(error, result);
// failure: callback(new Error("..."))
// success: callback(null, data)

The caller checks the error first, every time:

JS Error-first callbacks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two habits keep error-first code correct:

  • Always handle the error argument first, and return after handling it so the success code doesn't also run.
  • Call the callback exactly once. The return after the error call in checkStock matters: without it, the function would call back twice, once with the error and once with undefined.

Many Node.js core functions still use this style, such as fs.readFile(path, (err, data) => โ€ฆ), although Node.js now offers promise versions of most of them.

Callback hell

Callbacks work well for one step. Trouble starts when step two needs the result of step one, step three needs step two, and so on. Each step has to be nested inside the previous callback, and each level needs its own error check:

JS The pyramid of doom

Press Run (or Ctrl + Enter) to see the console output here.

No output.

It works, but look at the shape: the code drifts to the right in a widening triangle, often called the pyramid of doom. The problems are bigger than looks:

  • Hard to read. The logic flows down and right, and it's easy to lose track of which }) closes what.
  • Repeated error handling. Every level needs its own if (err). Forget one and errors vanish silently.
  • Hard to change. Running two steps in parallel, adding a timeout or retrying a step means restructuring the whole pyramid.

Flattening with named functions

You can tame the pyramid by giving each step a name and defining them separately. The nesting is still there logically, but each piece is readable on its own:

JavaScript
getUser(1, handleUser);

function handleUser(err, user) {
  if (err) return fail(err);
  getOrders(user, (err, orders) => handleOrders(err, orders, user));
}

function handleOrders(err, orders, user) {
  if (err) return fail(err);
  // ...and so on
}

function fail(err) {
  console.error("Something went wrong:", err.message);
}

This helps, but the deeper problems remain. That's what the next section is about.

Trusting someone else with your callback

When you pass a callback to a function, you hand over control of when and how often your code runs. This is sometimes called inversion of control, and it's the deepest problem with callbacks. A buggy or badly designed function might:

  • call your callback twice (the missing return bug above);
  • never call it, so your program waits forever with no error;
  • swallow an error instead of passing it on;
  • call it synchronously sometimes and asynchronously other times.

That last one is surprisingly nasty. Look at this cache, which answers immediately when it has the data and asynchronously when it doesn't:

JS Sometimes sync, sometimes async

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same code behaves differently depending on whether the cache was warm. The fix is to make the callback always asynchronous, for example by delivering cached values with queueMicrotask(() => callback(cache[item])). Promises guarantee this automatically: their callbacks always run asynchronously, even for values that are already available.

From callbacks to promises

Promises were designed to fix exactly these issues:

Callback problem How promises help
Nesting for each step Steps chain flat with .then()
Error check at every level One .catch() handles errors from any step
Callback called twice or never A promise settles exactly once
Sometimes sync, sometimes async Promise callbacks are always async (microtasks)
Hard to run things in parallel Promise.all() and friends

Here's a preview of the pyramid above, rewritten with promises and async/await. You'll learn every piece of it over the next lessons:

JavaScript
try {
  const user = await getUser(1);
  const orders = await getOrders(user);
  const details = await getOrderDetails(orders[0]);
  const shipping = await getShipping(details);
  console.log(`${user.name}, order ${details.id}: ${shipping}`);
} catch (error) {
  console.error(error.message);
}

Callbacks are still the right tool for events that happen many times, like clicks, key presses or messages, because a promise can only settle once. For "do one thing, then tell me the result", promises are the modern choice.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't getUser(id) simply return the user if it loads the data with setTimeout?

    An asynchronous callback runs after the outer function has already returned, so the result must be delivered through the callback.
  2. 2. In an error-first callback, how is success signalled?

    The first argument is the error; null means no error, and the result follows.
  3. 3. Why does checkStock need return right after callback(new Error(...))?

    Callbacks should be called exactly once; returning stops the function from continuing to the success path.
  4. 4. Which is a real problem with code that calls its callback synchronously sometimes and asynchronously other times?

    Code after the call may or may not have run when the callback executes, so behavior changes unpredictably. Always call back asynchronously.

Summary

  • An asynchronous callback is a function called later, after the function that received it has returned.
  • You can't return an async result; use it inside the callback.
  • The error-first convention passes (error, result); check the error first and call back exactly once.
  • Nesting dependent steps creates callback hell: hard to read, repetitive error handling, hard to change.
  • Handing over a callback means trusting the other code to call it once, asynchronously, with errors reported.
  • Promises fix these problems for one-off results; callbacks remain ideal for repeated events.

Next: Promises โ€” the object that represents a future value, and how to chain work with then, catch and finally.