DEV Community

Akshat Sharma
Akshat Sharma

Posted on

Day 24 of 30 of JavaScript

Hey reader👋 Hope you are doing well😊
In the last post we have talked about Promises. In this post we are going to discuss about Async/Await.
So let's get started🔥

Async/Await

Async/Await are powerful keywords in JavaScript used to handle Asynchronous operations with promises. They became feature of JavaScript with the release of ES8(ES2017). It is built on top of promises, and you can see it as an alternative syntax to promises.

Async Keyword

async is a JavaScript keyword used to create a function. The function created using async keyword will always return a promise.
Image description
So here we have created an arrow function using async keyword now we know that async returns a promise if the promise is resolved then data is printed.

Await Keyword

To use the await keyword, place it before a promise. It is an indicator for the async function to pause execution until that promise is settled.
Image description
So here our timerFunction returns a new promise that is resolved after 3 seconds. The asyncFunction uses the await keyword to wait for the promise returned by timerPromise to resolve. The await keyword pauses the execution of asyncFunc until the promise resolves. Once the promise resolves (after 3 seconds), the resolved value ("promise finished!") is assigned to the result variable.
Now here you can see that await makes sure that either the promise is resolved or rejected. Is it not similar to .then().
Await is similar to the .then() method.

The async keyword transforms a regular JavaScript function into an asynchronous function, causing it to return a Promise.
The await keyword is used inside an async function to pause its execution and wait for a Promise to resolve before continuing.
As we can do chaining of .then() method with Promise. We can also do same using await.
Image description

Advantages of Async/Await

  • Async and Await allow asynchronous code to be written in a synchronous style, making it easier to read and understand.

  • Using try/catch blocks with async/await makes error handling straightforward.

  • Async and Await help in avoiding nested callbacks and complex promise chains.

  • Debugging async/await code is more intuitive as it behaves like synchronous code.

I hope you have understood this blog well. In the next blog we are going to study about Event Loop which are very fundamental concept of Asynchronous Programming. Till then stay connected and don't forget to follow me.
Thankyou 🩵

Top comments (0)