Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 26, 2022 12:48 pm GMT

How to use Async/Await in JavaScript

Promises have been a great escape from callbacks, ever since they were introduced. Instead of callbacks hell, promises provide .then() API to chain multiple promises. However, in-case there are multiple dependencies, using .then becomes dreadful too and seems no much different than callbacks hell:

function getUser(userId){    return fetchUser(userId)        .then(user=>fetchUser(...))        .then(image=>fetchImage(...))        .catch(err=>console.error(err))}function displayPublicUser(userId){    getUser(userId)    .then(user=>{        if(user.isPublic){            displayUser(...)        }    })}

Introducing Async/Await

Async and Await keywords were introduced in ECMAScript 2017. Though they work as a synthetical sugar for Promises only, However, the asynchronous behavior of promises looks much like synchronous now and the code becomes much easier to handle. Comparing the above code using Async/Await will be like:

function getUser(userId){    const user = await fetchUser(...);    const image = await fetchImage(...);    return user;     }async function displayPublicUser(userId){    let user = await getUser(userId);    if(user.isPublic){        displayUser(...);    }}

Await must be inside Async function
In order to use await, make sure the parent function has async keyword attached to it. In case the function is not Async, then using Promises would work fine. Or there is an alternative to use IIFE wrapper to introduce Async keyword:

function getUser(userId){    return fetch(`https://some-api/user/${userId}`);}//WRONGconst user = await getUser(5);//CORRECT getUser(5).then(user=>{...}).catch(err=>{...})//OR//CORRECT(aync ()=>{    const user = await getUser(5);})()

Error Handling

It's recommended to handle errors prior to their appearance. I have got two of the most used approaches below:

async function displayUser(userId){    const user = await fetchUser(userId).catch(err=>{        console.log(err);        return null;    });    return user;}

The one I like and used most is:

async function displayUser(userId){    try{        const user = await fetchUser(userId)        return user;    }    catch(err){        console.error(err);        return null    }}

That's it for now, your comments are highly appreciated. See ya! .


Original Link: https://dev.to/ahmedgmurtaza/how-to-use-asyncawait-in-javascript-5c1m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To