JS Asynchronous Functions

Async and Await functions are also used to handle asynchronous operations. They use async and await keywords to handle Promises based functionality but in 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 functions.

  1. setTimeout
  2. setInterval
  3. Promises
  4. 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.

Async Function Example

PromiseĀ {<fulfilled>: 1}


    async function asyncFunction(){
        return 1;
    }

    asyncFunction()

Promise Example

PromiseĀ {<fulfilled>: 1}


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

Await

await keyword is used inside async function to wait for promise. await will wait for promise to fullfilled or reject and return the output.

await will pause async function execution till fullfill or rejected.

task done


async function asyncFunction(){

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

    res();
    
}            
    
    asyncFunction()