Async and await in JavaScript

Async and await in JavaScript

·

2 min read

Having knowledge of async and await is definitely the biggest advantage a programmer can have. What exactly is an async, await in JavaScript? JavaScript uses something called Event Loop which takes every action to the stack to get the job done. However, there are some operations that take more time to complete and this sort of operation can produce a serious issue in the performance of the code since they are asynchronous in nature, not happening at the same time. Then, how JavaScript is able to maintain non-blocking Input/Output while executing the code without ever breaking the thread?

There is something called Promise in JavaScript which makes the async code act synchronously, and Async, Await is the extension of the Promise in JavaScript. The Promise feature in JavaScript makes sure that the given asynchronous function always returns a value when executed completely. In JavaScript, there are two concepts you have to know before understanding async and await, Stack and Event Queue. When the code is executed, every operation that needs to be executed is taken to the Stack by the event loop. And the functions that are asynchronous in nature such as SetTimeout are taken to the Event Queue and the necessary operation is done on the function. Thus, when all the operations in Stack are executed properly, then with the help of the event loop the asynchronous function that is in Event Queue is pushed to the Stack and the required value is returned to the User. Therefore, we basically use the async function to inform the event loop that the function would need time to complete and not be a bottleneck in the performance of the code.

Now, let’s understand the async and await with the help of code:

The output of the above code would be:

Async and await are used mainly when you are fetching the data from the API but there are many other scenarios where async and await are needed. The alternate to async and await is Promise. However, using Promise in code creates a chaining function and makes our code cumbersome.

I hope you found this blog helpful. In the coming days, I will try to bring more blogs on the Event Loop and Promise.