Async and await are built on the top of promise to express asynchronous actions.
Inside the function, the await keyword can be applied to any Promise, which will defer the execution until the promise resolves.
Functions with the async keyword return a Promise. Function with the keyword async can perform asynchronous actions but still look synchronous.
The await method is used to wait for the promise to either get fulfilled or rejected.
General Syntax
Async function function_name(){
await some_promise()
}
Without async/await
let result = function(score){
return new Promise(function(resolve, reject){
console.log("Calculating results...")
if(score>50){
resolve("Congratulation! You have passed")
}else{
reject("You have failed")
}
})
}
let grade = function(response){
return new Promise(function(resolve, reject){
console.log("Calculating your grade...")
resolve("Your grade is A. " + response)
})
}
result(80).then(response => {
console.log("Result Received")
return grade(response)
}).then(finalgrade => {
console.log(finalgrade)
}).catch(err => {
console.log(err)
})
async function calculateResults(){
const response = await result(80)
}
So what the await keyword does. Until the result promise is resolved whatever the promise return get stored variable response.
With async/await
let result = function(score){
return new Promise(function(resolve, reject){
console.log("Calculating results...")
if(score>50){
resolve("Congratulation! You have passed")
}else{
reject("You have failed")
}
})
}
let grade = function(response){
return new Promise(function(resolve, reject){
console.log("Calculating your grade...")
resolve("Your grade is A. " + response)
})
}
async function calculateResults(){
try{
const response = await result(80);
console.log("Results Received");
const finalgrade = await grade(response)
console.log(finalgrade)
}catch(err){
console.log(err)
}
}
calculateResults()
Top comments (0)