Callback hell is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the other. By nesting callbacks
in such a way, we easily end up with error-prone, hard to read, and hard to maintain code. Soln: Best code practice to handle it.
This is a big issue caused by coding with complex nested callbacks. Here, each and every callback takes an argument that is a result of the previous callbacks. In this manner, The code structure looks like a pyramid, making it difficult to read and maintain.
⇒ Example of Callback Hell.
- Find User by username.
- Find Posts by userId.
- Find latest Post.
- Find Comments by postId.
- Find latest Comment.
- Find User of the last Commented User.
→ Implementation.
- /users?username=[username]
- /posts?user_id=[user_id]
- /comments?post_id=[post_id]
- /users?username=[username]
// GetData..
function getData(path, cb){
const data = []; // Somehow collect the Data..
cb(data);
}
function getUserNameFromComment(username){
getData(`/users?username=${username}`, (user) => {
getData(`/posts?user_id=${user._id}`, (posts) => {
getData(`/comments?post_id=${posts[0]._id}`, (comments) => {
getData(`/users?username=${comments[0].username}`, (user) => {
// Then 😃 you can get latest user of comment.
console.log(user);
});
});
});
});
}
getUserNameFromComment("Mohammad Asad");
Real Life Example of Callback Hell.
- We used https://jsonplaceholder.typicode.com this REST API website for using fake API to complete our example.
- And we used Axios library to handle HTTP request.
/// Real World Example with Fake REST API..
// Example of Callback Hell.
const Axios = require('axios').default;
const USERS_URL = 'https://jsonplaceholder.typicode.com/users';
const POSTS_URL = 'https://jsonplaceholder.typicode.com/posts';
const COMMENTS_URL = 'https://jsonplaceholder.typicode.com/comments';
function getFunc(URL, cb){
Axios.get(`${URL}`)
.then((response) => {
const { data } = response;
cb(data);
});
}
function getCommentByUser(username){
getFunc(`${USERS_URL}?username=${username}`, (user) => {
getFunc(`${POSTS_URL}?userId=${user[0].id}`, (posts) => {
getFunc(`${COMMENTS_URL}?postId=${posts[0].id}`, (comments) => {
const firstComment = comments[0];
console.log(firstComment);
});
});
});
}
getCommentByUser("Samantha");
So Let's see the solution of callback hell
Solution Of Callback Hell in JavaScript
Top comments (0)