Async and Await

Async and Await functions are also used to handle asynchronous operations. They use async and await keywords to handle Promises based functionality but in neater and cleaner way. Thus we can avoid using Promises and its chaining for asynchronous programming.

Asynchronous programming in JavaScript

To run a code asynchronously in JavaScript, we can use any one of following.

  1. setTimeout
  2. setInterval
  3. Events
  4. Promises
  5. Async and Await

Async

Async keyword is used before function keyword. Async function will always return a promise. Even if the return value of async function is not a promise, it will still be wrapped in a promise.

Thus, function will be called synchronously, but the return value will come asynchronously as it is a promise.

Async Function Example

Promise {<fulfilled>: 1}


    async function asyncFunction(){
        return 1;
    }

    asyncFunction()

Function return promise

Promise {<fulfilled>: 1}


    function asyncFunction(){
        return Promise.resolve(1);
    }
    
    asyncFunction()

Call Async Function

1


    async function asyncFunction(){
        return 1;
    }

    asyncFunction().then(i=>console.log(i));

use async as callback


document.querySelector('button').addEventListener("click",async (e)=>{
    console.log(e.target);
});

Await

await operator is used inside async function to wait for promise. await will wait for promise to be full filled or reject and return the output.

await can only be used in async function or top level of module.

  1. app start
  2. function called
  3. task done

async function asyncFunction(){

    let getData=function(){ 
        return setTimeout(function(){ 
            console.log("task done");
        });
    };
    
    let res=await getData;

    res();
    
    console.log("function called");
}            
    
    asyncFunction();
 
console.log("app start");    

Await Example using Promise

resolved after 1 sec


    function runAfter1Sec(){
        return new Promise((res)=>{
            setTimeout(()=>{
                res('resolved after 1 sec');
            },1000)
        })
    }

    async function resolve(){
        const p=await runAfter1Sec();
        console.log(p);
    }


Async Example using Fetch API

In this example below, we will use fetch api with async and await to give you a real life example of how to use Async Await

[{...}]


async function checkPin(){

const url="https://api.postalpincode.in/pincode/201301";
    
const api=fetch(url);

const res=await api.then(i=>i.json());

console.log(res);

}

checkPin();

Async Await with try catch

We can also use async await with try catch. The await will return promise, but it it fails, catch will pick the error. See example


async function checkPin(){
    
const url="https://api.postalpincode.in/pincode/201301";
        
try{
    const api=fetch(url);
    
    const res=await api.then(i=>i.json());
        
    console.log(res);
}
catch(err){
    console.warn(err);
}
    
}
    
checkPin();