Callback Hell
Nesting problems.
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.

- 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.
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);
});
});
});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.
| key | value |
|---|---|
| Callbacks | the original way |
| Deep nesting | hard to read |
| Errors | handled at every level |
| Promises | the 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