Async Await in Javascript
How to handle asynchronous execution in JavaScript with async, await
People new to Javascript often seem to be confused about how to handle the asynchronous nature of javascript. This article with help you understand the what, why and when of async await with practical and easy to understand examples.
Why was async/await introduced❔
Asynchronous programming surely has it’s benefits but it becomes a problem when it is required that certain piece of code executes only after the code above it is successfully executed, to handle this case JavaScript introduced async/await in ECMAScript 2017. Before the introduction of async/await there were promises. Async/Await uses promises itself but it is more easy to use async/ await than promises, in this article we see how we can use async/await with example.
Let us first Understand the Problem👀
Consider a scenario where you wish to have an orange juice made at home, you first need to buy oranges from store, cut and peel them and lastly add it to a juicer to make a refreshing orange juice, but these activities require some time and need to be done in the said order, let’s write down these steps into a code and associate a time with each task, this time will be setTimeout function of JavaScript.
We have made three functions for each of the task to achieve our final objective of making an orange juice by calling those functions in executeTheProcess() function and assigned time to each task with setTimeOut, it takes me more time to get oranges from a store and less time to cut/peel them off and add to the juicer. Now we run the executeTheProcess() function to start the oranges juice making process let’ see the output we get.
Ohh!!, that’s not how we make orange juice for sure!!. Let’s understand what happened here.
We wanted to buyOranges() function to execute first but it had a timeout of 2 secs and due to asynchronous execution of JavaScript this was added into eventloop and the next function was taken up for execution i.e cutAndPeelOranges() and addOrangesInJuicer(), by this time the 2 sec wait time was completed the buyOranges() function and it’s execution was complete but this has affected the steps to make juice to handle this very problem async/await was introduced in JavaScript.
Understanding async/await and how it helps solving the problem😁
Async/Await works with promises, function that returns a promise either resolve() on successful execution or can be rejected using reject(). Await keyword will hold the further execution until the promise is returned from the function. When a function is marked as async only then await keyword can be used inside it. By marking a parent function as async and marking the child function that returns a promise as await the execution can be kept on hold until its completion and then move on to the next line. Don’t worry if you still haven’t got what has to be done exactly, it will be clear once we see and understand the example below.
Let’s now solve our orange juice problem using async/await
We will return promise from each of our three child functions buyOranges(), cutAndPeelOranges(), addOrangesInJuicer() and mark the parent function executeTheProcess() as async and then call each of the above functions inside the parent function by marking them as await.
As seen in above code sample we have returned promise from each of the three functions and the function resolves the promise by using resolve() keyword and the output that we wish to print is also inside the resolve keyword, if instead of console you want to return certain value you can return the same using the resolve keyword as resolve(“some value”);.
Coming to executeProcess() function you can see that it has been marked as async and all the child functions inside it are marked as await, now the next line of code will be kept on hold until the execution of the previous line marked as await is not completed. So now buyOranges() will be executed first, the execution will hold on for 2 secs and then cutAndPeelOranges() will execute and execution will hold on for 1 sec and at last addOrangesInJuicer() will be executed. Let’s see the output now
Mission Accomplished !!! 😎🍊🍊🍊
Full Code Example:
Closure
We have learned how we can impart synchronous behavior to asynchronous nature of JavaScript code using async/await keywords with Promises.
If you found this article helpful give some claps👏 and share the knowledge with your friends and colleagues. Keep Learning📖 , Keep Growing📈