Async / Await
Async/await is syntactic sugar over Promises, making async code look and behave like synchronous code.
Basic Syntax
async function fetchUser(id) {
const response = await fetch(\`/api/users/\${id}\`)
const user = await response.json()
return user
}
// Arrow function version
const fetchUser = async (id) => {
const response = await fetch(\`/api/users/\${id}\`)
return response.json()
}
Error Handling with try/catch
async function loadData() {
try {
const response = await fetch('/api/data')
if (!response.ok) {
throw new Error(\`HTTP error: \${response.status}\`)
}
const data = await response.json()
return data
} catch (error) {
console.error('Failed to load:', error.message)
return null
} finally {
console.log('Request complete')
}
}
// Call it
const data = await loadData()
Parallel Requests
// Sequential (slow — waits for each)
const user = await fetchUser(1)
const posts = await fetchPosts(1)
// Parallel (fast — runs simultaneously)
const [user, posts] = await Promise.all([
fetchUser(1),
fetchPosts(1)
])
💡 Top-level await
In modern JavaScript modules, you can use await at the top level without wrapping in an async function.