Being a web developer you must have seen async and await in codes. And there are times when you forgot how it actually works, this is what happened with me, therefore I am writing this blog to have a quick recap on async and await on times when I need to. And I think there are many people like me who goes through this issue.
So, I got your back. This is beginner friendly as well. So just dive into it.
To understand async and await, we first need to understand promises in javascript.
Promise is just like a promise in real life.
For example : I promise to score good in upcoming test.
There can be two outcome of this promise, either promise will be resolved or it will be rejected. In the example, if I would score good in test, that means promise is resolved. But if I am not able to score good that means promise is rejected.
Promise are good to use when you want to do something that is going to take time in background. For example if you want to fetch an image from server.
Let’s see how we can create a promise using code in javascript.
let willScoreGood1 = new Promise((resolve,reject) ⇒ {
let score = 90
if(score≥90){
resolve(”You completed your promise, congrats”);
}else{
reject(’Failed’);
}
})
willScoreGood1
.then((message) ⇒ {
console.log(message);
}.catch(err ⇒ {
console.log(err);
})
let willScoreGood2 = new Promise((resolve,reject) ⇒ {
let score = 70
if(score≥90){
resolve(”You completed your promise, congrats”);
}else{
reject(’Failed’);
}
})
willScoreGood2
.then((message) ⇒ {
console.log(message);
}.catch(err ⇒ {
console.log(err);
})
In the code we have written two promise, first one willScoreGood1 and second one willScoreGood2 on calling first it will get resolved and corresponding to that we will receive a message in .then. On calling second promise we will get an error, which we will get in .catch.
Atlast we can see that using promises we can get the result of some task or the error for that task.
So now we know how promise works. Therefore we can move on to async and await.
Let’s start with async :
We use async keyword in front of a function to make it asynchronous, i.e. to take it out of normal sync of code.
For example :
// NORMAL FUNCTION
const greetings = () =>{
console.log("welcome everyone");
}
// ASYNC FUNCTION
const greeting = async () => {
console.log("welcome everyone");
};
greetings();
greeting();
When we write async in front of a function, then it will return values in form of promises.
At most of the times we use async and await together.
So let’s move to await keyword.
The advantage of an async function only becomes apparent when you combine it with the await
keyword. await only works inside async function
await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value.
CODE :
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
async function GreaterThan5(){
let value = getRandomArbitrary(0,10);
setTimeout(
if(value <= 5){
return 'small';
else{
throw new Error('Value is large');
},3000);
}
const asyncAndAwaitTogether = async () => {
const result = await GreaterThan5();
console.log(result);
}
asyncAndAwaitTogether()
.then(result => {
console.log(result);
}.catch(error => console.log(error);)
In the code, we have a function in the beginning that will return a random value in the range between min and max.
Then there is a async function GreaterThan5 and it will take some time to complete, when called, that’s why we have made it async.
After that there is one more async function asyncAndAwaitTogether, in this function we can see how async and await works together.
First thing we can notice in asyncAndAwaitTogether is that it is async, which means it will return a promise and inside the code we are calling GreaterThan5 function and before that we have written await, what await does here is that it stops the code till it gets any response, as soon as it get any result in form of resolve or reject. If the result is resolve then we will move to next line, but if we are getting reject in the result, then we will come out of function.
In the end we are calling asyncAndAwaitTogether, as it will return a promise we are using .then and .catch to get any kind of result.
Conclusion, on using async keyword before a function will make it asynchronous and it will return promises. We use await in async function to stop the code till the result is fetched.
That is all you need to get started with async and await,
Top comments (0)