AI Hints
Home›JavaScript Tutorial›Asynchronous Basics
JavaScript · Lesson 81 of 138

Callback Hell

Nesting problems.

⏱ 2 min read▶ Video at 1:37:59🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

The first way JavaScript handled async work was with callbacks. You pass a function that runs when the job is done. That works for one step. But when step two needs step one's result, and step three needs step two's, the code starts drifting to the right.

Callback Hell
From the video: Callback Hell
  • Callbacks for async
  • Fine for one step
  • Many steps drift right

The pyramid

Each fake job takes a value and a callback, and calls it back after a short wait. To do three steps in order, each one must go inside the last. Imagine ten steps, with error handling for each. This shape is called callback hell, or the pyramid of doom. Run it.

app.jsjavascript
function step(name, value, callback) {
  setTimeout(() => callback(value + 1), 100);
  console.log("Starting", name);
}

step("one", 0, (a) => {
  step("two", a, (b) => {
    step("three", b, (c) => {
      console.log("All done, result:", c);
    });
  });
});
Output
Starting one
Starting two
Starting three
All done, result: 3

The fix

Promises were added to JavaScript to fix this. They let you write async steps one after another, in a flat chain, with a single place for errors. And async and await, built on promises, make async code read almost like normal code. That's what's next.

keyvalue
Callbacksthe original way
Deep nestinghard to read
Errorshandled at every level
Promisesthe fix

Summary

Nested callbacks get hard to read and hard to handle errors in. Promises solve this. Let's meet them next.

Key takeaways
  • Callbacks work
  • But they nest
  • Promises fix it
Next up: Promises — a value from the future