What is async/await and how does it simplify asynchronous code?
TL;DR
async/await is a modern syntax in JavaScript that simplifies working with promises. By using the async keyword before a function, you can use the await keyword inside that function to pause execution until a promise is resolved. This makes asynchronous code look and behave more like synchronous code, making it easier to read and maintain.
Suspension and resumption
await pauses only the current async function; it does not block the JavaScript thread or make the surrounding caller wait synchronously.
The resumed code runs as a promise reaction, so it follows microtask ordering.
Introduction to async/await
Introduced in ECMAScript 2017 (ES8), async/await expresses Promise-based control flow with suspension at await.
Using the async keyword
The async keyword is used to declare an asynchronous function. When a function is declared as async, it automatically returns a promise. This means you can use the await keyword inside it to pause the execution of the function until a promise is resolved.
Using the await keyword
The await keyword can be used inside an async function and at the top level of an ES module. It suspends that async function or module until the value is fulfilled; it does not block the JavaScript thread. If the awaited promise rejects, await throws that reason, which can be caught with try...catch.
Simplifying asynchronous code
Before async/await, handling asynchronous operations often involved chaining multiple .then() calls, which could lead to "callback hell" or "pyramid of doom." async/await flattens this structure, making the code more readable and easier to maintain.
Example with promises
Example with async/await
Error handling
A rejection at an awaited expression throws within the async function, so a surrounding try...catch block can handle it.