async-await
async function
Declares a function that always returns a promise, letting you use await inside it to pause on other promises. A returned value fulfills the promise; a thrown error rejects it.
async function name(...args) { ... } Parameters
| Parameter | Purpose |
|---|---|
| return | Non-promise returns are wrapped in Promise.resolve |
| throw | Uncaught throws become promise rejections |
| forms | async function, async () => {}, async method(), class async methods |
Examples
async function getUser(id) {
const res = await fetch(`/users/${id}`);
if (!res.ok) throw new Error('not found');
return res.json();
} Returns a promise resolving to the parsed JSON, or rejecting with the thrown Error.
const loader = async () => {
const [a, b] = await Promise.all([loadA(), loadB()]);
return { a, b };
}; Async arrow function — same rules apply.
class Api {
async fetchToken() { return 'abc'; }
}
new Api().fetchToken().then(t => console.log(t)); Async methods work on classes and object literals too.
Gotcha
An async function ALWAYS returns a promise — return v does not return v to synchronous callers. Forgetting to await a call means you're passing a promise around, not the value.
Related
await
Pauses execution of the surrounding async function until the awaited promise settles, then resumes with its resolved value. If the promise rejects, await throws the reason, letting you use try/catch.
Top-level await
Allows using await outside of any async function at the top level of an ECMAScript module. The module's evaluation waits for the awaited promise, blocking importers until it settles.
try / catch with await
Since await throws when the awaited promise rejects, standard try/catch is the idiomatic way to handle async errors inside an async function. A finally block runs on both success and failure paths.
← All JS Promise reference · async/await vs promises vs callbacks