Async and Await Function
Written By: Avinash Malhotra
Updated on
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 a neater and cleaner way. Thus we can avoid using Promises and their chaining for asynchronous programming.
Asynchronous programming in JavaScript
To run a code asynchronously in JavaScript, we can use any one of following.
- setTimeout
- setInterval
- Events
- Promises
- Async and Await
Async
Async keyword is used before the function keyword. An async function will always return a promise. Even if the return value of an async function is not a promise, it will still be wrapped in a promise.
Thus, the function will be called synchronously, but the return value will be asynchronous 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 an async function to wait for a promise to resolve. await will wait for the promise to be fulfilled or rejected and return the result.
await can only be used in an async function or at the top level of a module.
1
2
4
3
async function asyncFunction(){
console.log(1);
await console.log(2);
console.log(3);
}
asyncFunction();
console.log(4);
Await with timer
- app start
- function called
- task done
async function asyncFunction(){
let getData=function(){
return new Promise((resolve)=>{
setTimeout(function(){
resolve("task done");
},1000);
});
};
let res=await getData();
console.log(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 and 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 and await with try-catch. The await will return a promise, but if it fails, catch will catch 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();
Using two await
We can also use two await statements in an async function. Each await statement pauses the function's execution until the promise it's awaiting resolves, then the function resumes. See example
async function checkPin(){
const url="https://api.postalpincode.in/pincode/201301";
try{
const api= await fetch(url);
if(!api.ok){ throw new Error("Can't parse data") }
const data=await api.json()
console.log( data );
}
catch(err){
console.warn(err);
}
}
checkPin();
Summary
Async and await provide a cleaner syntax for handling asynchronous operations in JavaScript, building on promises. Use the async keyword to define functions that return promises, and await to pause execution until promises resolve. This approach simplifies error handling with try-catch and is commonly used with APIs like Fetch for readable, sequential async code.