Async and Await

Learn how to use async/await in JavaScript to pause code execution until async calls complete and handle errors with try/catch when using Promises/async/await.

We have seen that the JavaScript runtime is single threaded and will push any asynchronous calls onto a particular queue within its memory, to be executed later.

Using Promises helps us to structure our code to ensure that we only execute a particular section of code once the asynchronous call has completed. We still need to bear in mind, however, that the JavaScript runtime will continue to process our code line by line. This quirk of the language can often lead to weird results or unwanted errors if we do not take care when writing code that will be executed asynchronously.

Oftentimes, however, we need to make a series of calls to one asynchronous function after another. In these cases, it would actually be far better if we could pause the execution of our code until the asynchronous code completes.

This is what the async and await keywords can do for us. We will explore how to mark functions with the async keyword in order to allow the use of the await keyword, which will actually pause execution of the code block until the Promise has completed.

Note: The async and await language features of JavaScript were adopted in the ES2017 language specification, meaning that only JavaScript runtimes that support this version can use the new async and await keywords. TypeScript, however, has incorporated support for these features for ES target versions all the way back to ES3. This means that we can safely use async and await within any body of TypeScript code, and it will behave as if the runtime was running ES2017. We can start using these language features now, and TypeScript will take care of the rest.

Await syntax

Let’s dive right in and see how to use async and await with an example. First up, a Promise that will delay for a second as follows:

Get hands-on with 1200+ tech skills courses.