Web Development

How Async/Await Works In JavaScript

Async/Await is the latest and greatest thing to come to JavaScript, allowing us to not only avoid callback-hell but ensure that our code is clean, shorter, more understandable to read. In this article, I will be showing, how Async/Await works with some easy examples.

Why async/await

Before async/await, callbacks and promises were used to handle asynchronous calls in JavaScript. Callbacks eventually lead to callback-hell. Promises were introduced to solve the famous callback-hell problem, but they have some complexity on their own.

  • Async/Await allows for a clean and concise codebase with fewer lines of code, less typing, and fewer errors. Ultimately, it makes complicated, nested code readable again.
  • Error handling with try/catch (in one place, rather than in every call)
  • Error stacks make sense, as opposed to the ambiguous ones that you receive from Promises, which are large and make it difficult to locate where the error originated. Best of all, the error points to the function from which the error came

How It Works

An async function returns a promise, like in this example:

When you want to call this function you prepend await, and the calling code will stop until the promise is resolved or rejected. One caveat: the client function must be defined as async

Here’s an example:

A Detailed Example

This is a simple example of async/await used to run a function asynchronously:

Output

Before
After
I did something //after 3s

Promise All The Things

Prepending the async keyword to any function means that the function will return a promise. Even if it’s not doing so explicitly, it will internally make it return a promise.

This is why this code is valid:

and it’s the same as:

The code is much simpler to read.

As you can see in the example above, our code looks very simple. Compare it to code using plain promises, with chaining and callback functions. And this is a very simple example, the major benefits will arise when the code is much more complex.

For example here’s how you would get a JSON resource, and parse it, using promises:

And here is the same functionality provided using await/async:

Multiple async Functions in Series

Async functions can be chained very easily, and the syntax is much more readable than with plain promises:

Output:

I did something and I watched and I watched as well

Easier Debugging

Debugging promises is hard because the debugger will not step over the asynchronous code. Async/await makes this very easy because to the compiler it’s just like synchronous code.

Read: How To Create An Icon Input Element Using HTML And CSS