DEV Community

Cover image for Understanding async and await in javascript
Avinash Kr
Avinash Kr

Posted on

Understanding async and await in javascript

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:

const url ="https://jsonplaceholder.typicode.com/posts/1";

fetch(url)
  .then(response=>response.json())
  .then(data=>console.log(data))
  .catch(error=>console.log(error));
Enter fullscreen mode Exit fullscreen mode

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.

//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);
    }
Enter fullscreen mode Exit fullscreen mode

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:

 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')
        }
    }
Enter fullscreen mode Exit fullscreen mode

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

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();
        }
Enter fullscreen mode Exit fullscreen mode

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.

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)