Callback Hell is a common problem in JavaScript that should be avoided for efficient coding.
In this post, we’ll understand what callback hell is, how it happens, and how to fix it using Promises.
What Are Callbacks?
Callback in JavaScript is the concept that says we can pass a function as an argument to another function.
For example, we have 2 functions and they shall only be called one by one and in a fixed sequence:
To ensure the second function is called only after the first function, we can use a callback like:
Note:
_Do not call the function in this way: first(1, second());
Parenthesis () indicate immediate execution of the function second. Hence, second will execute during the first function call and throw an error.
_
If the callback needs arguments, wrap it in an arrow function:
This was a simple example of 2 functions, but in real-world scenarios, we may have to deal with multiple functions that need to be executed in a specific sequence, each function depending on the output of another function.
Real-Life Example: Social Media App Flow
- Validate username
- If valid, check the password
- On success, fetch feed
- Click on a post → show reaction count
- Click on reaction → show user list
- Click on a user → show profile
- In code, each activity can be considered a function.
Here setTimeout function is used for asynchronous execution of code.
Now let’s see what happens when we use callbacks to execute the code:
This scenario gives rise to nested callbacks, also known as Callback Hell.
Callback Hell is nested callbacks stacked below one another. These callbacks often form a pyramid structure, hence also known as the Pyramid of Doom.
Using callbacks in this way leads to a style of programming that is difficult to understand and thus difficult to manage.
Callback Hell shall be avoided in real-world programming.
Solution: Promises
To solve this problem and produce more understandable and manageable code, we use Promises in JavaScript.
A Promise is an object in JavaScript used for eventually completing a task, but not immediately.
Syntax to define a Promise:
Here, resolve and reject are two callbacks or handlers provided by JavaScript.
Let’s rewrite our app logic using Promises:
The code to execute our functions using Promises:
Conclusion
Callback Hell is a common struggle in JavaScript, especially in real-world applications. But by using Promises, we can write cleaner, understandable, and more maintainable async code.