Turning JavaScript Asynchronously with Async-Await

Tosh
3 min readMay 8, 2021

--

Async/await was introduced in 2017 with ES8. It is a way to execute your code asynchronously without blocking the thread. Instead of using callbacks and promises the async/await syntax makes your code more readable and maintainable.

Creating an Async function

To create an async function we just need to add the async keyword before the function definition, like this:

When an async function is called, it always returns a Promise. When the Promise is resolved the async function will returns a value.

Await

The await keyword, pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value.

Let’s compare await syntax and .then() block.

AWAIT only works inside async functions within regular JavaScript code

Await is simply a cleaner way to write a promise within an async function. It improves readability immensely and hence the reason we use it and if we have a couple of asynchronous functions within our async block. Instead of chaining promises we could do this, which is much cleaner:

async/await make life easier

Failure

A Promise represents the eventual completion (or failure) of an asynchronous operation, and has 3 states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

Lets take a look at how to handle errors if the state is rejected

Try and catch

The common way to handle errors when using async-await, is try-catch. We encapsulate in the try block our code and if the promise is resolved we will get the return value however if it fails the catch block will handle any errors.

The catch() {} block is passed an error object, which we've called error; we can now log that to the console, and it will give us a detailed error message showing where in the code the error was thrown.

OR

If we don’t have try..catch, then the promise generated by the call of the async function hello() becomes rejected. We can append .catch to handle it.

Async class methods

We can also declare an async class method, just prepend it with async:

Summary

let’s recap, async/await is a cleaner syntax to write asynchronous Javascript code. It enhances readability and flow of your code.

Things to keep in mind while using async/await:

  • Async functions return a promise.
  • Await can only be used inside an async block.
  • Await waits until the function(“promise”) is fulfilled or rejected.

--

--