JavaScript
JavaScript async and await
async/await is syntax sugar over Promises that lets asynchronous code read top to bottom like normal code. Under the hood it is still Promises.
The basics
An async function always returns a Promise. await pauses inside that function until the awaited Promise settles.
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
Error handling
Wrap awaits in try/catch instead of .catch() chains.
try {
const user = await getUser(42);
console.log(user.name);
} catch (err) {
console.error('failed to load user', err);
}
Do not serialize by accident
Awaiting inside a loop runs requests one after another. If they are independent, fire them together with Promise.all.
// Slow: each await waits for the previous one
for (const id of ids) {
results.push(await getUser(id));
}
// Fast: all requests in flight at once
const results = await Promise.all(ids.map(getUser));
Parallel vs settled
Promise.allrejects as soon as any one rejectsPromise.allSettledwaits for every promise and reports each result, good when partial failure is acceptable
Common gotcha
forEach does not await. Use a for...of loop or map with .
