JavaScript – Async and Await Function

A async keyword before a function makes the function async function. It is a special syntax to work with promises in a more comfortable way. It is very easy to understand and use.

The only difference between a normal function and an async function is that async function always returns a promise.

Why to use async function if there is already promise method?

With the promise method, there is some complication that each and every time we have to write resolve() and reject(). Also due to this resolve and reject method, we could be able to use then() and catch() methods.

Promise were added to JavaScript in ECMAScript 2015. But later in 2017, async function is included to override some complication with promise function.

Let us understand with an example:

Normal Function:

function test(){
    return "Welcome to the Advance JavaScript Tutorial.";
}

console.log(test());

#Console Output
Welcome to the Advance JavaScript Tutorial.

Async Function: just added async keyword before function.

async function test(){
    return "Welcome to the Advance JavaScript Tutorial.";
}

console.log(test());

Output in Console

Now it will become a promise function. So in order to show result we should to use then() function.

async function test(){
    return "Welcome to the Advance JavaScript Tutorial.";
}

test().then((result) => {
    console.log(result);
});

#Console Output
Welcome to the Advance JavaScript Tutorial.

Also, above async function can be written as below:

let test = async function(){
    return "Welcome to the Advance JavaScript Tutorial.";
}

test().then((result) => {
    console.log(result);
});

#Console Output
Welcome to the Advance JavaScript Tutorial.

Async function using arrow function:

let test = async () => "Welcome to the Advance JavaScript Tutorial.";

test().then((result) => {
    console.log(result);
});

#Console Output
Welcome to the Advance JavaScript Tutorial.

Await

The keyword await before a function makes function to wait for a promise settles and returns its result. Await function can only be used within the async function.

Syntax

let value = await promise;

Let us understand with a simple way:

async function test(){
    console.log("First");
    await console.log("Second");
    console.log("Third");
}

test();
console.log("Fourth");
console.log("Fifth");

Here in the above example, the line where the await keyword is place before console.log(“Second”). It means that after this statement promise will wait to process further statement. JavaScript will execute rest of the code except test() until all the things are processed. Once the code below test() processed, then it will go back to await statement and process it then.

Flow of execution:

  • console.log(“First”);
  • console.log(“Second”);
  • console.log(“Fourth”);
  • console.log(“Fifth”);
  • console.log(“Third”);

Let us take another example:

Create a json file with some data:

employee.json

[
    {
        "name"  :   "Abhijeet Sinha",
        "dept"  :   "Technology",
        "salary":   90000
    },
    {
        "name"  :   "Mayank Manas",
        "dept"  :   "Operation",
        "salary":   85000
    },
    {
        "name"  :   "Gautam Gupta",
        "dept"  :   "Finance",
        "salary":   150000
    }
]

Now let’s fetch this json data with fetch() with async method.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Async/Await </title>
</head>
<body>
    <script>

        async function test(){
            return (await fetch("inc/employee.json")).json();
        }

        test().then((result) => {
            console.log(result);
        }).catch((error) => {
            console.log(error);
        });

    </script> 
</body>
</html>

Console:

We can also write async/await function within try catch method.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Advance JavaScript - Async/Await </title>
</head>
<body>
    <script>

        async function test(){
            try{
                const response = await fetch("inc/employee.json");
                const employee = await respone.json();
                return employee;
            }catch(error){
                console.log(error);
            }
        }

        test().then((result) => {
            console.log(result);
        });

    </script> 
</body>
</html>
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial