DEV Community

Cover image for How to use Async/Await in JavaScript
Ahmed Murtaza
Ahmed Murtaza

Posted on • Edited on

3

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

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:

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

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

//WRONG
const user = await getUser(5);

//CORRECT 
getUser(5)
.then(user=>{...})
.catch(err=>{...})

//OR

//CORRECT
(async ()=>{
    const user = await getUser(5);
})()
Enter fullscreen mode Exit fullscreen mode

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

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

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video