Async/Await Pair in Asynchronous Code
Learn to revolutionize the way we deal with asynchronous code using async/await.
We'll cover the following
async/await
Promises are a quantum leap ahead of callbacks. They allow us to write clean and readable asynchronous code and provide a set of safeguards that can only be achieved with boilerplate code when working with callback-based asynchronous code. However, promises are still suboptimal when it comes to writing sequential asynchronous code. The Promise
chain is indeed much better than having callback hell, but still, we have to invoke a then()
function and create a new function for each task in the chain. This is still too much for a control flow that’s definitely the most commonly used in everyday programming. JavaScript needed a proper way to deal with the comprehensive asynchronous sequential execution flow, and the answer arrived with the introduction in the ECMAScript standard of async functions and the await
expression (async/await for short).
The async/await dichotomy allows us to write functions that appear to block at each asynchronous operation, waiting for the results before continuing with the following statement. As we’ll see, any asynchronous code using async/await has a readability comparable to traditional synchronous code.
Today, async/await is the recommended construct for dealing with asynchronous code in both Node.js and JavaScript. However, async/await doesn’t replace all that we’ve learned so far about asynchronous control flow patterns; on the contrary, as we’ll see, async/await heavily relies on promises.
Async functions and the await
expression
An async function is a special type of function in which it’s possible to use the await
expression to “pause” the execution on a given Promise
until it resolves. Let’s consider a simple example and use the delay()
function we implemented in the “Creating a promise” section. The Promise
returned by delay()
resolves with the current date as the value after the given number of milliseconds. Here’s how we can use this function with the async/await
pair:
Get hands-on with 1200+ tech skills courses.