DEV Community 👩‍💻👨‍💻

Asad Anik
Asad Anik

Posted on

Solution Of Callback Hell In JavaScript

The Solution for callback hell we have figured out some concepts.

  1. Promise
  2. Async-Await

Promise can be the solution for the callback hell but after all it has own situation like the chaining of then, catch. And then we have figured out of this problem with Async-Await Concept. The Async-Await can help you from the multiple times chaining. Just write code like Synchronise way and it will handle the Asynchronous tasks as well.

Solution With Promise.

⇒ Example of Promise chaining.

  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]
// Solution Callback hell resolved with Promise..
const get = (url) => new Promise();

get(`/users?username=asadanik`)
    .then((user) => {
        return get(`/posts?user_id=${user.id}`);
    })
    .then((posts) => {
        const latestPost = posts[0];
        return get(`/comments?post_id=${latestPost.id}`);
    })
    .then((comments) => {
        const latestComment = comments[0];
        return get(`/users?username=${latestComment.username}`);
    })
    .then((user) => {
        console.log('Latest Comments user is -- ', user);
    })
    .catch(err => {
        console.log('ERR! of -- ', err);
    });
Enter fullscreen mode Exit fullscreen mode

Not permanent, but this is the solution of Callback hell which is nested over times. But in this case, this is not nested hell but also this is chaining hell of .this Promise. Not so much difference between this 2 examples of data retrieving. But this is not hell chaining, this is easy to maintain and readable. This problem will solve with Async Await.

Real Life Example of Promise with .then chaining

/// Real World Example with Fake REST API..
// Example of Promise.
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';

Axios.get(`${USERS_URL}?username=Samantha`)
    .then((userResponse) => {
        const { data: user } = userResponse;
        return Axios.get(`${POSTS_URL}?userId=${user[0].id}`);
    })
    .then((postsResponse) => {
        const { data: posts } = postsResponse;
        return Axios.get(`${COMMENTS_URL}?postId=${posts[0].id}`);
    })
    .then((commentsReponse) => {
        const { data: comments } = commentsReponse;
        const firstComment = comments[0];
        console.log(firstComment);
    })
    .catch(error => {
        console.log('ERR! of -- ', error);
    });
Enter fullscreen mode Exit fullscreen mode

So Let's see the solution of Promise Chaining
Solution Of Promise Chaining in JavaScript

Top comments (0)

Become a Moderator Do you want us to help make DEV a better place?

Fill out this survey and help us by becoming a tag moderator here at DEV.