DEV Community

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

Posted on • Updated on

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! 👋.

Top comments (0)