What is async/await?

async/await is syntax for working with promises that reads like synchronous code: an async function always returns a promise, and await pauses that function until a promise settles, giving you its value or throwing its error.

How it works

  • async function f() { return 1; } returns Promise<1>.
  • await somePromise suspends the function (not the whole program). The rest of the function continues as a microtask once the promise settles.
  • A rejected promise makes await throw, so you handle errors with ordinary try/catch.
  • await works with any "thenable" and with plain values (which are wrapped).

Where you can use await

  • Inside async functions (including arrow functions and class methods).
  • At the top level of ES modules (top-level await), e.g. to load config before exporting.

Sequential vs parallel

A common performance bug is awaiting independent operations one after another:

  • Sequential: const a = await getA(); const b = await getB(); takes the sum of both times.
  • Parallel: const [a, b] = await Promise.all([getA(), getB()]); takes the time of the slowest. Await in sequence only when the second call depends on the first.

Pitfalls

  • Forgetting await gives you a pending promise instead of the value.
  • forEach(async ...) does not wait. Use for...of or Promise.all.
  • Errors thrown after an await are rejections of the returned promise; the caller must handle them.

Code example

js
1const wait = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));
2
3async function getUser(id) {
4 await wait(30);
5 return { id, name: "Ada" }; // becomes the promise's value
6}
7async function getPosts(userId) {
8 await wait(30);
9 return [`post by ${userId}`];
10}
11
12console.log(getUser(1) instanceof Promise); // true - async functions return promises
13
14// Sequential: second call depends on the first
15const user = await getUser(1);
16const posts = await getPosts(user.id);
17console.log(user.name, posts); // Ada ["post by 1"]
18
19// Parallel: independent calls
20let t = Date.now();
21await getUser(1);
22await getPosts(1);
23const sequentialMs = Date.now() - t;
24
25t = Date.now();
26await Promise.all([getUser(1), getPosts(1)]);
27const parallelMs = Date.now() - t;
28console.log(`parallel is faster: ${parallelMs < sequentialMs}`); // parallel is faster: true
29
30// Forgetting await
31const notAwaited = getUser(2);
32console.log(notAwaited.name); // undefined - it's a Promise
33console.log((await notAwaited).name); // Ada

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app