Async JavaScript
Promises & Error Handling
A Promise represents an eventual fulfillment or rejection. Promise chains propagate returned values and thrown errors, letting async work be composed without nested callbacks.
- A Promise has a settled outcome
- Returning from
thentransforms the chain - Errors propagate until caught
- Floating promises are invisible work
- Promise errors are not synchronous try/catch unless awaited
async function loadUser(id) {
try {
const res = await fetch(`/api/users/${id}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return await res.json()
} catch (err) {
throw new Error(`Failed to load user ${id}`, { cause: err })
}
}