DEV Community

Bipon Biswas
Bipon Biswas

Posted on

JavaScript Async functions (async/await)

Async and await are built on the top of promise to express asynchronous actions.

Inside the function, the await keyword can be applied to any Promise, which will defer the execution until the promise resolves.

Functions with the async keyword return a Promise. Function with the keyword async can perform asynchronous actions but still look synchronous.

The await method is used to wait for the promise to either get fulfilled or rejected.

General Syntax

Async function function_name(){
  await some_promise()
}
Enter fullscreen mode Exit fullscreen mode

Without async/await

        let result = function(score){
            return new Promise(function(resolve, reject){
                console.log("Calculating results...")
                if(score>50){
                    resolve("Congratulation! You have passed")
                }else{
                    reject("You have failed")
                }
            })
        }
        let grade = function(response){
            return new Promise(function(resolve, reject){
                console.log("Calculating your grade...")
                resolve("Your grade is A. " + response)
            })
        }
        result(80).then(response => {
            console.log("Result Received")
            return grade(response)
        }).then(finalgrade => {
            console.log(finalgrade)
        }).catch(err => {
            console.log(err)
        })
Enter fullscreen mode Exit fullscreen mode

Output
Image description

        async function calculateResults(){
            const response = await result(80)
        }
Enter fullscreen mode Exit fullscreen mode

So what the await keyword does. Until the result promise is resolved whatever the promise return get stored variable response.

With async/await

 let result = function(score){
            return new Promise(function(resolve, reject){
                console.log("Calculating results...")
                if(score>50){
                    resolve("Congratulation! You have passed")
                }else{
                    reject("You have failed")
                }
            })
        }
        let grade = function(response){
            return new Promise(function(resolve, reject){
                console.log("Calculating your grade...")
                resolve("Your grade is A. " + response)
            })
        }
        async function calculateResults(){
            try{
                const response = await result(80);
                console.log("Results Received");
                const finalgrade = await grade(response)
                console.log(finalgrade)
            }catch(err){
                console.log(err)
            }
        }
        calculateResults()
Enter fullscreen mode Exit fullscreen mode

Output
Image description

Top comments (0)