article
freelance web application developer
async
await
vanilla-js
javascript
published on: 24 April 2022

What is Async?

The async keyword lets us define an asynchronous function. An asynchronous function returns a promise by default.

If the function returns a valid value then the promise is resolved otherwise if any error occurs in the function then its get rejected

Just like in the promises we can handle the promise from an async function using then and catch block

Here's how we do it


//Creating
const getData = async (value) => {
    if(value)
        return 'Got data';
    else
        throw 'Did not get data'
}

//Handling 
getData(true)
    .then((res) => console.log(res))
    .catch((err) => console.log(err))


What is await?

The await keyword allows us to wait until a promise is resolved or rejected.

It can only be used inside an async function.

Here's how we use it


const showData = async () => {
    //Waiting for the promise to get fulfilled
    const value = await getData(true);
    console.log("Value from promise: " + value)
}

showData();

How do we handle errors?

To handle errors we wrap the code in try/catch blocks

Let's see how we use it


const showData = async () => {
    try {
        //Waiting for the promise to get fulfilled
        const value = await getData(true);
        console.log("Value from promise: " + value);
    }
    catch(err) {
        console.log('Error: ${err}');
    }
}