What is Async/Await?
Async/Await is nothing but a special function to work with promises in a better way. As we have read about the Promises earlier that it is used to deal with the asynchronous operations. Similarly Async and await do the same but in a more comfortable fashion. It is very easy to understand.
Lets see below example –
function get() { return "Learn With Triveni"; } get();
This is the simple get() function. Here we are returning one string value i.e “Learn With Triveni”; When we will run this code there is nothing as unexpected. It will return simply that string value.
Output:
Async Function
async function get() { return "Learn With Triveni"; } get();
If you will run this code , then you will find that this code will return Promise instead of string value. It means that whenever we write async keyword before any function then its always return the promise. Let see its output
Await
await
makes JavaScript wait until that promise settles and returns its result. And it’s used only inside the async function. It wait for the asynchronous operations to be completed first then only next statement gets executed.
async function get() { let result = await (any asynchronous operation) // next operations // next operations } get();
So it’s just a sample code that how we can use the await keyword. As you can see await is used inside the async function. and after the await keyword there can be any asynchronous operation like any API call or promise operation etc. So it will wait for that operation to be completed first then the next line of operation will get execute.
Complete Example of async and await
async function get() { console.log("Before Promise"); let result = await getPromise(); console.log("After Promise"); console.log(result); } function getPromise() { return new Promise((resolve, reject) => { setTimeout(() => { console.log("Promise In Progress"); resolve("Promise Resolved"); }, 500); }) } get();
So we have taken the same example as previous one. We have created one async get() function. In which we have called getPromise() method and using await keyword, we will wait for that promise to be resolved.
Then we have created the getPromise() function. Inside that we have return a promise which get execute after 500ms. And at last we have simply call the get method.
For better understanding of sequence we have added the console logs. Through we that we can see where the exacts controls are going.
Now let see the output of it –
So in the output you can see firstly “Before Promise” has been print because it’s the first statement of our function. Then getPromise() method will get executed and it will print “Promise In Progress”. Once promise is returned we have another console log for “After Promise” and whatever data we have get from the promise so i.e “Promise Resolved”.
What happened if we will use await in regular function(without async)
function get() { let result = await getPromise(); }
With the same example try to run the code without async keyword. You will get the below error.
Because await is used only with the async function otherwise it will through the error.
Error Handling
We have seen the case when promise is resolved successfully. But what if promise will get rejected. Then how await will work in that case. So by using try catch block we can handle that. Let see in example.
async function get() { console.log("Before Promise"); try { let result = await getPromise(); console.log("After Promise"); console.log(result); } catch(error) { console.log(error); } } function getPromise() { return new Promise((resolve, reject) => { setTimeout(() => { console.log("Promise In Progress"); reject("Promise Rejected"); }, 500); }) } get();
So we have taken the same example but this time instead of resolving the promise we have reject the promise. And inside the get() method added try catch block. If promise resolve successfully then try block will get executed. If promise is rejected then catch block will execute. So as getPromise() has rejected the promise so catch block will handle that error. Let see the output below –
You can see firstly “Before Promise” is printed then getPromise() is called and it prints “Promise In Progress”. After that promise is rejected so it has passed “Promise Rejected” message. In catch block simply this message will print.
Advantages of using Async and Await
- It makes the code more readable as compare to promise and callbacks
- Error handling became more easy
- We can debug the code easily
This is all about async/await function. Visit the asynchronous operations and promises to make the async/await more clear.