DEV Community

Asad Anik
Asad Anik

Posted on

Callback Hell In JavaScript

Callback hell is a phenomenon that afflicts a JavaScript developer when he tries to execute multiple asynchronous operations one after the otherBy 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.

  1. Find User by username.
  2. Find Posts by userId.
  3. Find latest Post.
  4. Find Comments by postId.
  5. Find latest Comment.
  6. 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");
Enter fullscreen mode Exit fullscreen mode

Real Life Example of Callback Hell.

/// 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");
Enter fullscreen mode Exit fullscreen mode

So Let's see the solution of callback hell
Solution Of Callback Hell in JavaScript

Top comments (0)