Async and Await
async and await are syntax for working with promises as if the code were synchronous. An async function always returns a promise. Inside it, await promise pauses that function until the promise settles, then gives you its value (or throws its error), while the rest of the program keeps running. The result is asynchronous code that reads top to bottom, uses ordinary try...catch, loops and if statements, and is far easier to follow than promise chains or callbacks.
In One Minute
async function f() { ... }always returns a promise;return xfulfills it withx,throw errrejects it.await ppauses theasyncfunction (not the whole program) untilpsettles, then returns the value or throws the error.- Handle errors with
try...catcharoundawait. awaitin sequence runs operations one after another; start them first andawait Promise.all(...)to run them in parallel.awaitworks at the top level of ES modules (top-level await).
Async Functions
Syntax
async function name(params) { ... }
const fn = async (params) => { ... };
const obj = { async method() { ... } };
class C { async method() { ... } }Example
async function getBalance(name) {
return name === "Navika" ? 120 : 0;
}
const result = getBalance("Navika");
console.log(result instanceof Promise);
result.then((balance) => console.log("balance:", balance));
async function fails() {
throw new Error("Server unavailable");
}
fails().catch((err) => console.log("rejected:", err.message));true
balance: 120
rejected: Server unavailableAn async function's return value becomes the promise's value; a throw becomes a rejection. Callers can use .then or await.
await
await can only be used inside an async function (or at the top level of a module). It takes a promise, pauses until it settles, and evaluates to the fulfilled value:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function loadSummary() {
console.log("loading student...");
const student = await wait(20, { name: "Srihitha", fee: 450 });
console.log("loading payments...");
const payments = await wait(20, [200, 150]);
const paid = payments.reduce((a, b) => a + b, 0);
return `${student.name} owes $${student.fee - paid}`;
}
console.log("before");
const summary = loadSummary();
console.log("after calling loadSummary (it is paused, not blocking)");
console.log(await summary);before
loading student...
after calling loadSummary (it is paused, not blocking)
loading payments...
Srihitha owes $100Explanation: loadSummary runs synchronously until its first await, then pauses and returns a pending promise, so "after calling" prints next. While it waits, other code runs. Each await resumes the function when its promise fulfills. The final await summary waits for the whole thing.
await on a non-promise value simply continues with that value (after one microtask tick), so await 5 is 5.
Error Handling with try...catch
A rejected promise makes await throw, so ordinary try...catch works, including for errors from any number of awaited steps:
async function charge(amount) {
await new Promise((r) => setTimeout(r, 10));
if (amount > 500) throw new Error(`Card limit exceeded for $${amount}`);
return `C-${amount}`;
}
async function pay(amount) {
try {
const confirmation = await charge(amount);
return `Paid, confirmation ${confirmation}`;
} catch (err) {
return `Payment failed: ${err.message}`;
} finally {
console.log(`(cleanup for $${amount})`);
}
}
console.log(await pay(120));
console.log(await pay(900));(cleanup for $120)
Paid, confirmation C-120
(cleanup for $900)
Payment failed: Card limit exceeded for $900This is the big win over callbacks: try, catch and finally work exactly as with synchronous code.
Errors You Don't Catch
If an async function throws and nobody catches the rejection, it becomes an unhandled rejection: browsers log it as an error, and Node.js (since version 15) terminates the process. Every promise needs a handler somewhere: a try...catch around its await, or a .catch on the final call.
Sequential vs Parallel
Each await waits before the next line starts. That's right when a step needs the previous result, and wasteful when steps are independent:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const getStudents = () => wait(60, ["Navika", "Srihitha", "Advitha"]);
const getTotal = () => wait(60, 655);
let start = Date.now();
const students = await getStudents();
const total = await getTotal();
const sequential = Date.now() - start;
start = Date.now();
const [students2, total2] = await Promise.all([getStudents(), getTotal()]);
const parallel = Date.now() - start;
console.log(students.length === students2.length && total === total2);
console.log(`sequential took about 120 ms: ${sequential >= 115}`);
console.log(`parallel took about 60 ms: ${parallel < 100}`);true
sequential took about 120 ms: true
parallel took about 60 ms: trueExplanation: in the sequential version, the second request doesn't even start until the first finishes. In the parallel version, both functions are called first (starting both operations), and Promise.all waits for both. The total time is the longest single request, not the sum.
Loops with await
await works naturally in for and for...of loops, processing items one at a time:
const save = (p) => new Promise((resolve) => setTimeout(() => resolve(`saved ${p.name}`), 5));
const payments = [{ name: "Navika" }, { name: "Srihitha" }, { name: "Advitha" }];
for (const p of payments) {
console.log(await save(p));
}
const results = await Promise.all(payments.map((p) => save(p)));
console.log(results.length, "saved in parallel");saved Navika
saved Srihitha
saved Advitha
3 saved in parallelUse the for...of version when order matters or the server can't handle many requests at once; use Promise.all with map when they're independent. Don't use forEach with an async callback: forEach doesn't wait for promises (see the async mistakes lesson).
Top-Level await
In ES modules (<script type="module">, .mjs files, or files in a "type": "module" package), await can be used at the top level, outside any function:
const response = await fetch("/api/config.json");
export const config = await response.json();
// Modules that import this one wait until config is ready.In classic scripts and CommonJS files, wrap the code in an async IIFE: (async () => { ... })();. (This course's Try it runner runs your code inside an async function, which is why top-level await works in every example.)
async with Other Features
class Tracker {
#cache = new Map();
async balanceOf(name) {
if (this.#cache.has(name)) return this.#cache.get(name);
const value = await new Promise((r) => setTimeout(() => r(name.length * 10), 5));
this.#cache.set(name, value);
return value;
}
}
const tracker = new Tracker();
console.log(await tracker.balanceOf("Navika"), await tracker.balanceOf("Navika"));
const names = ["Srihitha", "Advitha"];
const balances = await Promise.all(names.map(async (n) => `${n}: $${await tracker.balanceOf(n)}`));
console.log(balances);60 60
['Srihitha: $80', 'Advitha: $70']Async methods, async arrow functions as map callbacks, and private fields all combine freely.
In Practice
The Fee Tracker's page load: fetch the student and settings in parallel, then (sequentially, since it needs the student) fetch the payments, with one try...catch and a finally that hides the spinner:
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const api = {
student: (id) => wait(20, { id, name: "Advitha", fee: 120 }),
settings: () => wait(20, { currency: "USD" }),
payments: (student) => (student.id === 3 ? wait(20, [45, 30]) : Promise.reject(new Error("Payments service unavailable"))),
};
async function loadPage(id) {
console.log("spinner on");
try {
const [student, settings] = await Promise.all([api.student(id), api.settings()]);
const payments = await api.payments(student);
const balance = student.fee - payments.reduce((a, b) => a + b, 0);
return `${student.name}: ${balance} ${settings.currency} due`;
} catch (err) {
return `Error: ${err.message}`;
} finally {
console.log("spinner off");
}
}
console.log(await loadPage(3));
console.log(await loadPage(4));spinner on
spinner off
Advitha: 45 USD due
spinner on
spinner off
Error: Payments service unavailableCommon Mistakes
Forgetting await. const data = fetchData() gives a pending promise, not data. Linters can catch this.
Awaiting independent operations one by one. Start them together and await Promise.all(...).
await inside forEach. It doesn't wait. Use for...of or Promise.all(arr.map(...)).
Unhandled rejections. Every async call needs a try...catch or .catch somewhere up the chain.
Under the Hood
An async function is compiled into something like a generator (a function that can pause and resume) driven by promises. Calling it creates a new promise and starts running the body. At each await, the engine evaluates the operand, wraps it with Promise.resolve if needed, registers the function's continuation as a reaction on that promise, saves the function's local state, and returns control to the caller. When the awaited promise settles, the continuation is queued as a microtask; running it restores the saved state and resumes after the await, either with the value or by throwing the reason at that point. V8 optimized this in 2018 so that awaiting a native promise costs only a single microtask tick (earlier engines took three), and it records async stack traces, so errors show the chain of awaits that led to them even though the original call stack has unwound.
Interview Corner
What does an async function return?
Always a promise. A returned value fulfills it (a returned promise is adopted), and a thrown error rejects it. Even async function f() { return 1; } returns Promise<1>.
Does await block the thread?
No. It suspends only the enclosing async function, returning control to the event loop. The rest of the function resumes as a microtask when the awaited promise settles. Other code, events and rendering continue meanwhile.
How do you run awaits in parallel?
Start the operations without awaiting them (calling the async functions creates the promises), then await them together: const [a, b] = await Promise.all([getA(), getB()]). Sequential await getA(); await getB(); waits for each before starting the next.
Practice
Challenge: Write async function totalPaid(ids, fetchPayment) that fetches every payment in parallel and returns the sum, where fetchPayment(id) returns a promise of an amount. Test it with a fake fetchPayment.
Show solution
async function totalPaid(ids, fetchPayment) {
const amounts = await Promise.all(ids.map((id) => fetchPayment(id)));
return amounts.reduce((sum, a) => sum + a, 0);
}
const fakeFetch = (id) => new Promise((resolve) => setTimeout(() => resolve(id * 25), 10));
console.log(await totalPaid([1, 2, 3], fakeFetch));150Key Takeaways
| Pattern | Code |
|---|---|
| Async function | async function load() { ... } |
| Wait for a result | const data = await getData() |
| Handle errors | try { await x() } catch (err) { ... } |
| Parallel | const [a, b] = await Promise.all([getA(), getB()]) |
| One at a time | for (const id of ids) await save(id) |
| Script without modules | (async () => { ... })() |
Was this tutorial helpful?