Async/Await in Javascript
Async/Await is a new feature that has been added to ES8 which allows us to write synchronous looking code but performing the task asynchronously. Async/await can be used instead of promise chaining.
Let's see an example program for async/await:
Output
Task 1 completed Task 2 completed Task 3 completed
In the example above, we have declared 3 functions that returns promise. taskOne() and taskTwo() functions will return response by taskThree() function rejects and returns an error.
In order to use async/await we declare the executeTasks() function as async function. Now this function can wait for the promise to execute by using the ???await' keyword.
The taskOne() function returns ???Task 1 completed' which will be logged to console. Similary taskTwo() function will return ???Task 2 completed' which will be logged to the console and finally the taskThree() function will reject with error message ???Task 3 interupted'. Now the rejected value will be caught in the catch block of executeTask() function and will be logged to the console.
The Async function will return a promise by default. So the above promise has been modified to
Now the above code will console a promise object rather than ???Task 1 completed'. To solve this we can use the below code
Now we shall rewrite the first example that was written with promise to async function.
Output
Task 1 completed Task 2 completed Task 3 completed
This produces the same output like above method. Here the taskThree() function has manually thrown an error which will be caught by the catch block of executeTask() function and logs in console.