Callback hell is code where async callbacks are nested inside each other, deeper and deeper. Promises and async/await turn it into flat code.
Before promises, async APIs took a callback to call when the work was done. A common form was the Node style (err, result) => {}. When each step needs the result of the step before, callbacks nest inside callbacks. The code forms a pyramid that moves to the right.
The problems are more than looks:
- You must repeat error handling at every level.
- It is easy to forget to pass an error on.
- Loops and parallel steps are hard to write.
- A third-party API might call your callback twice, or never. This is called inversion of control: you hand control of your code to someone else.
Promises fix this. The function returns an object you can chain. You get a flat list of then calls with a single catch for errors. Helpers like Promise.all handle parallel work.
async/await goes further. You write the same flow as normal top-to-bottom code, with normal try/catch and loops.
- Callback hell is dependent callbacks nested deeply inside each other.
- Error handling must be repeated at every level, which causes mistakes.
- Inversion of control means you trust other code to call your callback correctly.
- Promises give flat chains with one
catch. async/awaitreads like synchronous code.
Read more
- Introduction: callbacks (https://javascript.info/callbacks)javascript.info