Async Await in JavaScript

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Video Tutorial

Promises and Async Await

Overview

Promises were introduced in ES2015 to handle asynchronous operations or we can say to manage callback functions in JavaScript.

But as time changed the limitations like syntax complexity of Promises were solved by the extension introduced for Promises i.e., Async await in Javascript. Async await javascript is based on promises that make the code easier to read and write. Async await javascript works synchronously but looks like asynchronous code.

Prerequisites

Before getting started with Async await in Javascript you must have good knowledge about promises. It is because async/await works on the concept of promises.

Why were Async await in Javascript Introduced?

Suppose you ordered pizza from dominos and you have to buy shoes from a nearby showroom. So instead of wasting time and waiting till the pizza is prepared in the meantime you go and buy the shoes.

This is how async/await works.

To solve the callback problem, Promises were introduced in ES2015.

Async was introduced to overcome the limitations of promises. Promises used asynchronous code to solve a problem but had their complexity as well as syntax complexity.

Asynchronous code looks like asynchronous(the code gets executed in a sequence that means the next statement has to wait until the previous statement is executed) code but works synchronously.

The Async Keyword

If you are working in a kitchen, you probably would have gone through it if you are doing multiple works at the same time.

For example, you are making a pizza. So the process will be first preheating the oven. While the oven is preheating, you cut the veggies and grated cheese and make the base of the pizza ready. That means your time doesn't get wasted.

This is how async/await work.

The async keywords stand for asynchronous. It was introduced to solve the issues that were faced by promises. So, async works on Promises.
The work of async is to make a function work without the need of freezing the complete program.

The async keyword is used before the function will return a value. Or we can say that it works as resolved/fulfilled in promise.

Syntax

Example

Let us look at the basic code and understand how async works.

Result

The above program gives the result as Resolve.

The Await Keyword

The Await keyword is used inside the async function. The work of await is to wait for the execution thread to wait until the result is resolved and then returns the result. As await is used inside an async function, it only makes it wait, not the complete program.

Syntax

Example

Let us understand it with a simple example where the result is resolved in 1 second.

Result

As result, we get an alert displaying Resolved. That means our code is executed within 1 second. The execution of the function gets paused at the (*) line for 1 second because we have set it to await.

Rewriting Promise Code with Async/Await

Here let's see the difference between promise and async code syntax.

Code execution with promise

Result

From the above code, and we get the result first and then it says the promise is executed.

But, hey what if we use an async function and add await in it too?

Let's look at that code too by rewriting the above code.

Result

Here, the function returnPromises() returns a promise after 1s after being resolved; this means it shows synchronous behavior because we are making the thread wait for 1s and then executing the result.

How Does Async/Await Work?

Evolving the world means making it easier for us humans to read and understand. Therefore to understand the code and write it in a simpler way async/await were introduced.

Async keyword was introduced to make the code more efficient than promise and call back functions.

The main work of async is to return a promise.

We use the async keyword before the function and make that function return a promise. The await keyword can only be used inside an async function, if it is used outside the code will throw an error.

Awaiting a Promise.all() call

Suppose multiple promises need to be fulfilled, if all the promises are executed then it will take time in execution until each of them is resolved, so, to overcome this issue Promise.all() is introduced that takes an array of promises as an argument and waits for each promise to be fulfilled and then returns a single promise.

All the promises mustn't depend on each other.

  • If all the promises are fulfilled then we call the then() handler that contains all arrays of promises in the same order as passed in promise.all().
  • If any promise gets rejected then the catch() handler is called with the error that was thrown by the promise.

Syntax

Example This is a simple example based on Promise.all().

Result

As the result, we get an array of all the promises combined as a single promise. It returns a single promise only when all the promises are resolved. If any one of them throws an error, the catch handler will get implemented. Since all our promises are fulfilled, we get an array as an output.

How to Handle Async/Await Slowdown?

The slowdown means the delay in the execution of a program that can occur due to multiple promises being called in the function. It may be due to multiple arrays or the length property of an array that causes slowdown. To overcome this issue we use the Promise.all() method. Promise.all() method is already discussed above. To use Promise.all(), all the promises must be independent.

Handling errors

We have only seen the promises getting resolved without any error. But what if there is an error?

Sometimes the promise might take some time to reject. Therefore we get a slight delay before the error is displayed by await.

To overcome this issue we use the try...catch.. method(try-catch works the same way as a throw).

Syntax

For example

Result

The above code will run into an error because the URL doesn't exist. It will throw TypeError

If we don't have a try-catch method then we can append catch while calling the function.

Result

Async/await Class Methods

To create an object we have to create a class. You can do so by creating a class and declaring an async function inside it.

Example

Let us understand it with a simple example.

Result

We will get 1 as a result. As it is mentioned in the return statement in the class example.

Await Accepts “thenables”

Thenable in javascript is used to enable async/await function that has a then() function. We can say that all promises are thenable but vice versa is not true. It might happen that the third party object is not a promise but it is compatible with a promise and supports a .then handler that we can use thenable with await. We can use the thenable object(that has a callable then() handler).

For example

Result

In the console, we get 20 after 1s. We get 20 because the value is set as 10 and it is multiplied by 2 in resolve.

Benefits of Using Async Function

There are few benefits or async over promise and the callback function.

  • Code readability - It makes code easy to write and read because async functions can be chained easily using promise.all() makes it easier to read than with plain promises.
  • We can handle errors easily. Errors can be easily handled using try-catch handlers.
  • Async function makes debugging simpler because to the compiler the code looks synchronous.

Conclusion

  • Async await in Javascript works on the concept of Promise. Async defines the fulfillment of a promise and returns a promise.
  • We use async before the function that allows us to return promise-based codes.
  • Await can be used only in async functions. It is used to make the function wait until and unless the promise is resolved or rejected and then returns the result.
  • We use the try...catch method for error handling in async/await.
  • Async/await makes asynchronous code that is easy to read and write.

Learn More: