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 then transforms the chain
  • Errors propagate until caught
  • Floating promises are invisible work
  • Promise errors are not synchronous try/catch unless awaited
Promise chain propagation
A chain is a pipeline of fulfillment and rejection states.
Propagating useful async errors
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 })
  }
}
Add context at the boundary, but preserve the original cause.
Sources
  • MDN JavaScript Guide and ReferencePromises
  • The Modern JavaScript TutorialPromises, async/await
  • Node.js Documentation and Learn Node.jsDiscover Promises in Node.js