-
Notifications
You must be signed in to change notification settings - Fork 0
27 Async Await
Biswajit Sundara edited this page Aug 18, 2023
·
1 revision
The purpose of async / await is to simplify the promise handling.
-
asyncfunctions always return a promise. -
awaitwaits until the promise is resolved. - The await keyword can only be used inside an async function.
- await is like
yield - The behavior of async / await is similar to combining generators and promises.
//This function returns promise object
async function logName(name) {
return name;
}
//We are extracting the promise object using then
logName("Biswajit").then((result) => {
console.log(result);
})async function logName(name) {
const transform = new Promise((resolve, reject) =>{
setTimeout(()=>resolve(name.toUpperCase()),5000);
});
//1. yield promises using await
const result = await transform;
//2. Return a promise
return result;
}
logName("Biswajit").then((result) => {
console.log(result);
})This will wait until the promise for transform object is fulfilled. The promise will be assigned to the result and then we are unpacking the promise object using then.
The same example mentioned before but using arrow function.
const logName = async (name) => {
const transform = new Promise((resolve, reject) =>{
setTimeout(()=>resolve(name.toUpperCase()),5000);
});
//1. yield promises using await
const result = await transform;
//2. Return a promise
return result;
}
logName("Biswajit").then((result) => {
console.log(result);
})The error handling in async await is really simple. We need to use try catch blocks
const logName = async (name) => {
try{
const transform = new Promise((resolve, reject) =>{
setTimeout(()=>resolve(name.toUpperCase()),2000);
setTimeout(()=>reject("There is an error"),1000);
});
//1. yield promises using await
const result = await transform;
//2. Return a promise
return result;
}
catch(error){
console.log(error);
}
}
logName("Biswajit").then((result) => {
console.log(result);
})The promise will send reject in 1 second, so it will throw error and will be caught in the catch block.
const fun1 = ( async ()=>{
const num = new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log("Hello");
resolve(5);
},2000);
})
const result = await num;
return result;
});
//We can unpack the value from promise object using then
fun1().then((data)=>{
console.log(data);
})
//We can assign the value returned from await function
const fun2 = async ()=>{
const num1 = await fun1();
console.log(num1);
}
//Invoke the function
fun2();