Javascript Async/ Await

We use the async keyword with a function to represent that the function is an asynchronous function. The async function returns a promise. The syntax of async function is:-

async function name(parameter1, parameter2, ...paramaterN) {
    // statements
}

Here, name is name of the function and parameters is parameters that are passed to the function.

Input:-
<script>
	   const getData = async() => {
         var data = "Hello!!";
         return data;
    }
        
    getData().then(data => document.write(data));
</script> 

Output:-


Await Keyword

Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result and only makes the async block wait. The syntax to use await is:-

let result = await promise;

Following example illustrate the use of await in promises.

Input:-
<script>
	   let promise = new Promise(function (resolve, reject) {
            setTimeout(function () {
            resolve('Promise resolved')}, 4000); 
        });
        async function asyncFunc() {
            let result = await promise; 
            console.log(result);
            console.log('Hello!!');
        }
        asyncFunc();
</script> 

Output:-


Error Handling

While using the async function, we write the code in a synchronous manner. And we can also use the catch() method to catch the error. The other way we can handle an error is by using try/catch block. For example,

Input:-
<script>
	   let promise = new Promise(function (resolve, reject) {
         setTimeout(function () {
         resolve('Promise resolved')}, 4000); 
    });
    async function asyncFunc() {
         try {
           let result = await promise; 
           console.log(result);
        	 }   
         catch(error) {
           console.log(error);
        	 }
    }
    asyncFunc();
</script>

Output:-


Benefits of using async function

Below are the benefits of using async function within Javascript:-

  • The code is more readable than using a callback or a promise.
  • Error handling is simpler.
  • Debugging is easier.