JavaScript async/await
Write asynchronous code that reads like synchronous control flow
Overview
async/await is syntactic sugar over Promises. An async function always returns a Promise. await pauses execution until a Promise settles, without blocking the main thread.
Syntax / Usage
async function loadDashboard(userId) {
try {
const user = await fetchUser(userId)
const posts = await fetchPosts(user.id)
return { user, posts }
} catch (error) {
console.error('Dashboard failed:', error)
throw error
}
}
// Parallel requests
async function loadAll() {
const [users, products] = await Promise.all([
fetchUsers(),
fetchProducts(),
])
return { users, products }
}
// Top-level await (ES modules)
const config = await fetch('/config.json').then((r) => r.json())
Examples
Sequential steps with clear error handling:
async function signup(formData) {
const user = await api.createUser(formData)
await api.sendWelcomeEmail(user.email)
return user
}
Loop with await (sequential processing):
async function processFiles(paths) {
const results = []
for (const path of paths) {
results.push(await readFile(path))
}
return results
}
Common Mistakes
- Using
awaitin a loop when parallelPromise.allwould be faster - Forgetting
try/catcharound awaited calls - Marking non-async functions
asyncunnecessarily - Awaiting non-Promise values works but adds noise—only await async operations
See Also
promises fetch-api functions closures