DEV Community

Asad Anik
Asad Anik

Posted on

Solution Of The Promise Chaining In JavaScript

When we are gonna solve the problem of Callback Hell, then there is another type of problem which is not so good for coding style and handle the code. That is the chaining of then, catch multiple times. So the solution is to using Async-Await for handle asynchronous task with synchronous way.

β‡’ This Async Await will solves the Callback Hell and the Promise chaining Hell problems. Our Async function should returns the Promise stand alone 😎.

β‡’ Example of Async Await.

  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]
// Example of Async Await..
async function getUserName(username){
    const mainUser = await get(`/users?username=${username}`);
    const posts = await get(`/posts?user_id=${mainUser.id}`);
    const comments = await get(`/comments?post_id=${posts[0].id}`);
    const user = await get(`/users?username=${comments[0].username}`);
    console.log(user);
}

getUserName('Mosammat Akhi');
Enter fullscreen mode Exit fullscreen mode

Basically the Async Await is the system where you can see the Asynchronous code just like same as the Synchronous code. πŸ’πŸ»Β We declared this complex Callback Hell and Promise .this chaining Hell with simple like Synchronous style of Asynchronous Task πŸ™„.

β†’ So if we handle the Error to see and manage it.

// Example of Async Await..
async function getUserName(username){
    try {
            const mainUser = await get(`/users?username=${username}`);
            const posts = await get(`/posts?user_id=${mainUser.id}`);
            const comments = await get(`/comments?post_id=${posts[0].id}`);
            const user = await get(`/users?username=${comments[0].username}`);
            console.log(user);

    } catch (ERR) {
        console.log('ERR! when try to fetching data -- ', ERR);
    }
}

getUserName('Rakhiyaatul Kubra');
Enter fullscreen mode Exit fullscreen mode

This code can handle or see the Error when you needs like Promise .catch chain. We can use Try-Catch block instead of Promise.

But without Promise you can’t understand the Async Await tasks.

Real life Example of Async Await.

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

async function getCommentByUser(username){
    try {
        const { data: mainUser } = await Axios.get(`${USERS_URL}?username=${username}`);
        const { data: posts } = await Axios.get(`${POSTS_URL}?userId=${mainUser[0].id}`);
        const { data: comments } = await Axios.get(`${COMMENTS_URL}?postId=${posts[0].id}`);
        const firstComment = comments[0];
        console.log(firstComment);

    } catch (error){
        console.log('ERR! from -- ', error);
    }

}

getCommentByUser('Samantha');
Enter fullscreen mode Exit fullscreen mode

β‡’ Another Real Life Example of Async Await.

Async Await function returns the Promise it-self. So we can make .then .catch chaining of Async Await function calling.

// Another Real Life Example..
const Axios = require('axios');
const URL = "https://jsonplaceholder.typicode.com/users";

// Async Await to get data..
async function getUsers(){
    const { data: users } = await Axios.get(URL);
    return users;
}

// Make .then .catch promise from Async Await function..
// Async function returns the Promise.
getUsers().then((users) => {
    console.log(users);
}).catch((error) => {
    console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)