Solution Of The Promise Chaining In JavaScript
Tags: javascript, beginners, programming, tutorial
Published: 2022-10-10 10:14:32

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]

```jsx
// 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');
```

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

```jsx
// 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');
```

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

- We used [https://jsonplaceholder.typicode.com](https://jsonplaceholder.typicode.com/users) this REST API website for using fake API to complete our example.
- And we used [Axios](https://axios-http.com/docs/intro) library to handle HTTP request.

```jsx
/// 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');
```

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

```jsx
// 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);
});
```