Skip to main content

Command Palette

Search for a command to run...

How to use Async and Await Keyword in Javascript

Published
2 min read

Hello Everyone👋🏼, Hope you and your loved ones are well😇

First, we will talk about the definition and later will explain async and await with a very simple example.

Introduction

Async and Await keyword is used to make promise easier to write which makes the code easier to read.

A function that is declared with the async keyword will always return a promise. An example of the declaration of an async function is given below:

const function  = async () => {

}

Await keyword makes a function wait till it gets a promise. Await keyword can only be declared inside an async function. A declaration example is given below.

let p = await promise

Example

Now let's take a simple example, of how can one make a promise easier to write using async and await keyword.

const add = (x,y) => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(x+y)
        },2000)     
    })
}


add(10, 20).then((ans)=> {
    return add(ans, 30)
}).then((ans1) => {
    console.log(ans1)
}).catch((error) => {
    console.log(error)
})

Now, we write the same example as above by using the async-await keyword.

const add = (x,y) => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            resolve(x+y)
        },2000)     
    })
}


const doAddition = async () => {
    const sum = add(2,10)
    const sum1 = add(11,sum)
    const sum2 = add(14,sum1)
    return sum2
}


doAddition.then((result) => {
    console.log("Addition result-> ",result)
}).catch((e) => {
    console.log(e)
})

If you need to do the same addition task multiple times without using the async-await keyword you need to call the then method multiple times.

Now, just by writing a separate function for doing addition and using the async-await keyword, we brought that call to multiple then() method to just one, and made the code simpler and easier to read.

Hope that I was able to explain you.

Happy Coding👨🏼‍💻👩🏼‍💻!!