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 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.

  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)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!