Understanding async and await in javascript
Tags: javascript, beginners, tutorial
Published: 2021-06-13 19:26:05

Async await is another way of handling promises in JavaScript.
One of the main advantage of using it is clean code.

In this article we will understand with examples and use cases.

In general, we use .then().catch() to handle promises:
```javascript
const url ="https://jsonplaceholder.typicode.com/posts/1";

fetch(url)
  .then(response=>response.json())
  .then(data=>console.log(data))
  .catch(error=>console.log(error));
```
Let's handle it using async await

We can write using function statement or function expression. Both will be valid, only difference is use of anonymous function in function expression.
```javascript
//function statement
    async function getPosts(){
        const response = await fetch(url);
        const data = await response.json();
        console.log(data);
    }
    
    //function expression
    const getPosts = async function(){
        const response = await fetch(url);
        const data = await response.json();
         console.log(data);
    }
```
*Please keep in mind that we are not handling with error in the above code, the value of response will only be return when operation is success.*

## HOW CAN WE HANDLE ERROR IN ASYNC AWAIT ?? ##

To handle error in async await, we can use 'try and catch'

Look at the code below for the same:
```javascript
 async function getPosts(){
        try{
            const response = await fetch(url);
            const data = await response.json();
            console.log(data);
        } catch{
            console.log('something went wrong in getting post')
        }
    }
```
##HOW TO HANDLE MULTIPLE PROMISES USING ASYNC AWAIT ?? ##

suppose we have to fetch user, post and comment in async await.

Look at the code below and guess how will it work
```javascript
const user = 'https://jsonplaceholder.typicode.com/users/1';
const post = 'https://jsonplaceholder.typicode.com/posts/1';
const comment = 'https://jsonplaceholder.typicode.com/comments/1';

     const multiFetch = async()=>{
           const userRes= await fetch(user);
           const userData = await userRes.json();

           const postRes= await fetch(post);
            const postData = await postRes.json();

           const commentRes = await fetch(comment);
           const commentData = await commentRes.json();
        }
```
*In the above line of code javascript will wait on every line to complete its work, then move to next line. In simple words it will first fetch user, once its is completed, js will fetch post, then comment. Javascript will work synchronously.*

##CAN WE MAKE MULTIPLE FETCH REQUESTS AT THE SAME TIME??##

We can fetch multiple at the same time, every request will be made independently or it will not block other request.

```javascript
const multiFetch = async()=>{
  try{
     const allRes = await Promise.all([fetch(user),fetch(post)],fetch(comment)]);
     const response =  allRes.map(res=>res.json());
     const finalData = await Promise.all(response);
     console.log(data);
    } catch{
        console.log("promise not fulfilled")
    }
}
```
*In above code, every request will be made in parallel, and value will be returned once resolved, in case of error code in catch will run.*

I hope it might helped you to get idea of how to use async await in javascript.