The Solution for callback hell we have figured out some concepts.
- Promise
- 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.
- 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]
// 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);
});
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
- 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 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);
});
So Let's see the solution of Promise Chaining
Solution Of Promise Chaining in JavaScript
Top comments (0)