Async JavaScript
async/await
async functions always return Promises, and await pauses the current async function until a Promise settles while allowing the event loop to continue running other work.asyncwraps return values in Promisesawaitunwraps fulfillment or throws rejection- Await pauses the function, not the whole runtime
- Sequential awaits serialize work
- Top-level await changes module loading
| Pattern | Behavior | Use when |
|---|---|---|
| await a(); await b(); | b starts after a finishes | b depends on a |
| const pa = a(); const pb = b(); await Promise.all([pa, pb]) | a and b run concurrently | independent work |
| for await (...) | Consumes async sequence | Stream/incremental data |
// Slower if independent:
const user = await loadUser(id)
const projects = await loadProjects(id)
// Faster if independent:
const [user2, projects2] = await Promise.all([
loadUser(id),
loadProjects(id),
])