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 =”…


This content originally appeared on DEV Community and was authored by Avinash Kr

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));

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);
    }

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')
        }
    }

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();
        }

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")
    }
}

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.


This content originally appeared on DEV Community and was authored by Avinash Kr


Print Share Comment Cite Upload Translate Updates
APA

Avinash Kr | Sciencx (2021-06-13T19:26:05+00:00) Understanding async and await in javascript. Retrieved from https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/

MLA
" » Understanding async and await in javascript." Avinash Kr | Sciencx - Sunday June 13, 2021, https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/
HARVARD
Avinash Kr | Sciencx Sunday June 13, 2021 » Understanding async and await in javascript., viewed ,<https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/>
VANCOUVER
Avinash Kr | Sciencx - » Understanding async and await in javascript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/
CHICAGO
" » Understanding async and await in javascript." Avinash Kr | Sciencx - Accessed . https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/
IEEE
" » Understanding async and await in javascript." Avinash Kr | Sciencx [Online]. Available: https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/. [Accessed: ]
rf:citation
» Understanding async and await in javascript | Avinash Kr | Sciencx | https://www.scien.cx/2021/06/13/understanding-async-and-await-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.