**await** makes asynchronous code look synchronous. It can only be used inside `async` functions (or at the top level of ES modules). When a Promise rejects, await **throws** the rejection — handle it with try/catch. Multiple `await` calls execute sequentially; use `Promise.all()` for parallel execution.
1Understanding await
await makes asynchronous code look synchronous. It can only be used inside async functions (or at the top level of ES modules). When a Promise rejects, await throws the rejection — handle it with try/catch. Multiple await calls execute sequentially; use Promise.all() for parallel execution.
Avoid sequential awaits that could run in parallel: 'const [a, b] = await Promise.all([fetchA(), fetchB()])' is 2x faster than 'const a = await fetchA(); const b = await fetchB()'.
async function getUserWithPosts(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(userId);
return { user, posts };
} catch (e) {
console.error('Failed:', e.message);
return null;
}
}
// Parallel (2x faster)
async function getUserWithPostsFast(userId) {
const [user, posts] = await Promise.all([
fetchUser(userId),
fetchPosts(userId)
]);
return { user, posts };
}2Practical Example
Here is a real-world application of await showing how it is used in production JavaScript code.
// Top-level await (ES modules only)
const config = await fetch('/config.json').then(r => r.json());
console.log(config.apiUrl);3Best Practices
Follow these guidelines when working with await:
1. Use try/catch around await for error handling
2. Run independent awaits in parallel with Promise.all()
3. Always mark functions that use await as async
Tip: Avoid sequential awaits that could run in parallel: 'const [a, b] = await Promise.all([fetchA(), fetchB()])' is 2x faster than 'const a = await fetchA(); const b = await fetchB()'.
async function getUserWithPosts(userId) {
try {
const user = await fetchUser(userId);
const posts = await fetchPosts(userId);
return { user, posts };
} catch (e) {
console.error('Failed:', e.message);
return null;
}
}
// Parallel (2x faster)
async function getUserWithPostsFast(userId) {
const [user, posts] = await Promise.all([
fetchUser(userId),
fetchPosts(userId)
]);
return { user, posts };
}