Async Await is syntactical sugar wrapped around to make the implementation of promises easier, If you don't understand how promises works make sure you check out this post
The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs.
Let's jump into an example that will help us understand Async Await in a better way.
function newRequest(place) {
return new Promise((resolve,reject)=>{
if(place === 'home') {
resolve('You have reached home');
} else {
resolve("You haven't reached home");
}
})
}
function makeRequest(response) {
return new Promise((resolve,reject)=>{
console.log(response);
resolve(`Current location:- ${response}`);
})
}
newRequest('home').then(response =>{
return makeRequest(response);
}).then(makeResponse => console.log(makeResponse)).catch((err) => console.log(err));
//Output
//"You have reached home"
//"Current location:- You have reached home"
In the above example, the newRequest
function returns a promise that takes a parameter place based on which promise is resolved. The makeRequest
function returns a promise which is always resolved. The two functions are executed in order the second promise waits for the first one.
The above code can be simplified by with the use of Async/Await
function newRequest(place) {
return new Promise((resolve,reject)=>{
if(place === 'home') {
resolve('You have reached home');
} else {
resolve("You haven't reached home");
}
})
}
function makeRequest(response) {
return new Promise((resolve,reject)=>{
console.log(response);
resolve(`Current location:- ${response}`);
})
}
async function checkLocation() {
try {
const response = await newRequest('home');
const processed = await makeRequest(response);
console.log(processed);
} catch (err) {
console.log(err);
}
}
checkLocation();
//OUTPUT
// "You have reached home"
// "Current location:- You have reached home"
In this example, checkLocation
is declared using the async keyword. The async keyword tells javascript that the following function is asynchronous. The checkLocation
works exactly the same as the promises returning the same output. As you can see it looks a lot better and readable than the first example.
Error handling is done with the help of a try-catch block.
Async Await is just like promises in a way makes it easier to write promises.
Thank you for your time. That's All folks
Top comments (0)