GGistDev

Promises in JavaScript

Promises represent the eventual result (or failure) of asynchronous operations.

Creating promises

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve(42), 100)
})

Use helpers: Promise.resolve, Promise.reject.

then / catch / finally

Chain with then; handle errors with catch; finally runs regardless.

p.then(v => v * 2)
 .then(v => console.log(v))
 .catch(err => console.error(err))
 .finally(() => console.log('done'))

Promise combinators

Run in parallel and collect results.

await Promise.all([a(), b()])          // fail-fast
await Promise.allSettled([a(), b()])   // always resolves
await Promise.race([a(), b()])
await Promise.any([a(), b()])          // first fulfilled (ES2021)

Error handling

Errors in then handlers become rejected promises; always end chains with catch or handle in await with try/catch.

try {
  const v = await p
} catch (e) {
  // handle
}

Anti-patterns

  • Avoid the Promise constructor when you already have promises
  • Don’t mix callbacks and promises; promisify old APIs

Abort and timeouts

Use AbortController with fetch and libraries that support signals.

const c = new AbortController()
const res = await fetch('/api', { signal: c.signal })
// c.abort()

Summary

  • Chain with then/catch/finally; prefer await in async functions
  • Use Promise.all/any/allSettled/race for coordination; support abort where possible