async / await
Write asynchronous code that reads like synchronous code.
Syntax
async function f() { const v = await promise; }async and await are modern syntax for working with promises.
- Mark a function
asyncto allowawaitinside it. awaitpauses until a promise resolves, then gives you its value.
This makes asynchronous code read top-to-bottom, like ordinary code.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Write a data-fetching function that reads like synchronous code using async/await instead of .then chains.
- Await a database query result before computing derived values that depend on it.
- Use try/catch around an await call to handle API errors without a .catch chain.
More examples
Basic async function
Awaits the fetch response and JSON parsing in sequence, returning the user's name.
async function getUser(id) {
const res = await fetch("https://jsonplaceholder.typicode.com/users/" + id);
const user = await res.json();
return user.name;
}
getUser(1).then(console.log);try-catch with async-await
Wraps the await calls in try-catch to handle both network failures and non-OK HTTP responses.
async function loadData(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json();
} catch (err) {
console.error("Failed:", err.message);
return null;
}
}Sequential awaits for dependent calls
Awaits each dependent async call in order so orders are fetched only after the user is known.
async function fetchUser(id) { return { id, name: "Alice" }; }
async function fetchOrders(id) { return [{ id: "o1", total: 50 }]; }
async function buildProfile(userId) {
const user = await fetchUser(userId);
const orders = await fetchOrders(user.id);
return { user, orders };
}
buildProfile(1).then(console.log);
Discussion