Previously we had a small introduction on Promises which are used in asynchronous events and getting data after an event occurs, Async Await is a JavaScript API that allows you to write asynchronous code in a synchronous manner so that your code is easier to read and debug.
Async Await is just different syntax for using Promises, they use promises in the background. Most browsers support Async Await, you can get the full list here.
Promises are some event that takes a little bit of time to resolve and pass data to you. An simple example is getting data from an remote API, when you make the request to the API, you have to wait for the request to go from your device to the server, the server then processes your request and then sends back the result.
Promise ‘then’ method is called then the promise is completed and you can handle the data if you like, similarly Async Await allows you to wait till the event finishes so that you can continue.
Methods
Async Await has only 2 methods
Async
If you want to use Async Await, you have to declare the function as an async function.
Normal function
function getImage(url){………}
Async function
async function getImage(url){………}
Await
Await make the execution of the program pause at the statement until the promise is resolved.
var image = await getImage(url);
In the above line, the image variable will get the data only after the getImage promise is resolved.
Example
Lets now look at an example to see the syntactic differences between Promises and Async Await.
function gotMyMoney(){
return new Promise((resolve, reject)=>{
setTimeout(_=>{
var randomNum = Math.floor(Math.random()*100+1);
if(randomNum % 2 == 0){
resolve(true);
}else{
resolve(false);
}
}, 4000);
})
}
gotMyMoney().then(status=>{
if(status){
console.log("user has money");
}else{
console.log("user does not have money");
}
})
The above code shows how to use Promises to handle an async event, we first have a function gotMyMoney which returns a Promise, it resolves either true or false after 4 seconds.
Next we call the function and then when the promise is resolved, we log whether the user has money or not.
function gotMyMoney(){
return new Promise((resolve, reject)=>{
setTimeout(_=>{
var randomNum = Math.floor(Math.random()*100+1);
if(randomNum % 2 == 0){
resolve(true);
}else{
resolve(false);
}
}, 4000);
})
}
async checkStatus(){
var status = await gotMyMoney();
if(status){
console.log("user has money");
}else{
console.log("user does not have money");
}
}
checkStatus();
In the above code snippet , we perform the same code using Async Await, the gotMyMoney function is the same, we create a new async function checkStatus as Await will only work inside async functions, next we write the code as if the code is syncronous, this is the main advantage of Async Await.
Error Handling
If the promise that contains the data fails or rejects, then the await statement will throw an error, you can handle it in two ways
try catch
Simply surround the await statement in a try catch block and handle the promise rejection in the catch block
Example
async function checkStatus(){
try{
var getData = await getDataFromURL(url);
}catch(e){
console.log('the getDataFromURL promise failed)
}
}
catch
You can also add a catch block to handle the promise failing
Example
async function checkStatus(){
var getData = await getDataFromURL(url).catch(e){
console.log('the getDataFromURL promise failed)
}
}