JavaScriptEasy
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; }returnsPromise<1>.await somePromisesuspends the function (not the whole program). The rest of the function continues as a microtask once the promise settles.- A rejected promise makes
awaitthrow, so you handle errors with ordinarytry/catch. awaitworks with any "thenable" and with plain values (which are wrapped).
Where you can use await
- Inside
asyncfunctions (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
awaitgives you a pending promise instead of the value. forEach(async ...)does not wait. Usefor...oforPromise.all.- Errors thrown after an
awaitare rejections of the returned promise; the caller must handle them.
Code example
js
1const wait = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));23async function getUser(id) {4 await wait(30);5 return { id, name: "Ada" }; // becomes the promise's value6}7async function getPosts(userId) {8 await wait(30);9 return [`post by ${userId}`];10}1112console.log(getUser(1) instanceof Promise); // true - async functions return promises1314// Sequential: second call depends on the first15const user = await getUser(1);16const posts = await getPosts(user.id);17console.log(user.name, posts); // Ada ["post by 1"]1819// Parallel: independent calls20let t = Date.now();21await getUser(1);22await getPosts(1);23const sequentialMs = Date.now() - t;2425t = Date.now();26await Promise.all([getUser(1), getPosts(1)]);27const parallelMs = Date.now() - t;28console.log(`parallel is faster: ${parallelMs < sequentialMs}`); // parallel is faster: true2930// Forgetting await31const notAwaited = getUser(2);32console.log(notAwaited.name); // undefined - it's a Promise33console.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.