Async/Await
- Pronunciation
- AY-sink uh-WAYT
In short
Async/await is a syntax for writing asynchronous code that reads like ordinary step-by-step code, pausing at each await until a promise or task finishes.
What is async/await?
Async/await is a pair of keywords that makes asynchronous code, meaning code that waits for things like network requests or file reads, easier to write and read. You mark a function with async, and inside it you put await in front of an operation that takes time. The function then pauses at that line until the result is ready and continues with the value.
In JavaScript, async/await is built on promises. An async function always returns a promise, and await waits for a promise to settle, giving you its value or throwing its error. Because of this, you can handle failures with a regular try/catch block instead of chaining .catch() calls.
Pausing with await does not freeze the whole program. While one function is waiting, the runtime keeps doing other work, such as responding to clicks or handling other requests, and resumes the function when its result arrives. It's like putting a pot of water on the stove and chopping vegetables while it heats, instead of standing and staring at the pot.
The async/await pattern also exists in many other languages, including C#, Python, Rust, Kotlin, and Swift. A common mistake is awaiting independent operations one after another, which makes them run in sequence; if they don't depend on each other, start them together and wait for all of them with Promise.all.
At a glance
Key takeaways
asyncmarks a function as asynchronous; in JavaScript it always returns a promise.awaitpauses only the current function, not the whole program, until a promise settles.- Errors can be handled with ordinary
try/catchblocks. - Use
Promise.allto run independent operations in parallel instead of awaiting them one by one.
Example
// An async function can use await inside it
async function loadUser(id) {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new Error("HTTP " + response.status);
return await response.json(); // wait for the body to be parsed
} catch (error) {
console.error("Could not load user:", error);
}
}
// Run two independent requests at the same time
const [first, second] = await Promise.all([loadUser(1), loadUser(2)]);Readers ask
Does await block the main thread?
No. await pauses only the async function it is in; the rest of the program, including the browser's user interface, keeps running. The function resumes once the awaited promise settles.
Can I use await outside an async function?
In modern JavaScript, you can use top-level await directly in ES modules. In classic scripts and CommonJS files, await must be inside an async function.
What is the difference between async/await and promises?
Async/await is syntax built on top of promises, not a replacement for them. It lets you write the same promise-based logic in a more linear, readable style.
See also
- PromiseProgramming Fundamentals, p. 46A promise is an object that represents the eventual result of an asynchronous operation, letting code react to success or failure once the work completes.
- CallbackProgramming Fundamentals, p. 7A callback is a function passed as an argument to another function, which then calls it later, for example when a task finishes or an event happens.
- ConcurrencyProgramming Fundamentals, p. 12Concurrency is a program's ability to make progress on several tasks in overlapping time periods, such as serving many users at once rather than one at a time.
- JavaScriptWeb Development, p. 24JavaScript is the programming language that runs in web browsers to make pages interactive, and it also runs on servers through runtimes like Node.js.
- FunctionProgramming Fundamentals, p. 21A function is a named, reusable block of code that performs a specific task, optionally taking inputs called parameters and returning a result.
- APIBackend & APIs, p. 2An API is a set of rules that lets one piece of software request data or actions from another in a predictable, documented way.
Sources
Spotted a mistake or something missing on this page?Suggest an edit