Async/Await in JavaScript

Async/Await in JavaScript

We use the then() and catch() method to handle promises. But we have another way of handling promises and that is async/await. Sometimes, using too many then() and catch() creates messy and unreadable code. async/await is just a more elegant way of handling promises than then() & catch() and it is easier to read & write.

To use async/await, we have to use async before a function and await keyword before the promise inside the async function.

await keyword makes javascript wait until the promise settles and returns its value.

An async function always returns a promise.

await is always used inside the async function.

Using async/await

Let's understand this with an example, First, we will create a promise then we will handle that promise with both methods-

  • then() & catch()

  • async/await

Creating a Promise =>

// Promise created
function myPromise(){
    return new Promise(function(resolve,reject){
        let data = true
        if(data){
            setTimeout(()=>resolve("Data fetched"), 2000)
        }else{
            reject("Error occurred")
        }
    })
}

let promise = myPromise()

Handling the promise with then() & catch() =>

promise.then((res)=>console.log(res)).catch(err=>console.log(err)).finally(()=>console.log("runs anyway"))
// Data fetched
// runs anyway

Handling the promise with async/await =>

async function promiseHandler(){
    try{
        let res = await promise
        console.log(res)
    }
    catch(err){
        console.log(err)
    }
    finally{
        console.log("runs anyway")
    }
}

promiseHandler() 
// Data fetched
// runs anyway

Using then() & catch() with async function

We know that the async function always returns a promise object.

To handle that promise returned by the async function we can use then() & catch().

async function myPromise(){
    return "Data fetched"
}

console.log(myPromise()) // Promise { 'Data fetched' }

// Handling the promise returned by async function myPromise using then()
myPromise().then(res=>console.log(res)) // Data fetched

Final Words

And that’s it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next blog.✌️