Promises
promises
Code Snippets
Sleep with a Promise
Pausing async code is a one-line problem until you need cancellation, a typed signal, or to reuse the helper across files. This snippet starts with the canonical `setTimeout` Promise wrapper, then adds `AbortSignal` support so callers can cancel waits cleanly. Drop it into any toolkit and stop reaching for `setTimeout` callbacks in async functions.
Timeout a Promise
A promise that never settles will leak handles and stall UI flows; wrapping it with a deadline turns a bug into a recoverable error. This snippet shows the classic `Promise.race` pattern, then upgrades it to clean up the timer on success and to forward an `AbortSignal` so cancelled work stops doing real I/O. Use it around any `fetch`, DB call, or third-party SDK that does not expose a native timeout option.
Run Async Functions in Sequence
`Promise.all` runs every task at once, but sometimes you need strict ordering: a write that must come after a read, a paginated API that uses the previous response as a cursor, or a queue of migrations that must not interleave. This snippet covers the serial `for...of` loop, the equivalent `reduce`-based one-liner, and a chain helper that pipes each result into the next step. Pick the shape that matches how your data flows.
Partition allSettled Results
`Promise.allSettled` is the right call for partial-success workflows, but its `{ status, value, reason }` shape is awkward to consume directly. This snippet wraps it with a partitioner that returns `{ values, errors }` so the happy path stays simple, then layers in input-aware error reports that pair each failure with the original argument. Use it for fan-out fetches, batched writes, or any spot where one bad item should not poison the whole batch.
Poll Until a Condition Is True
Polling shows up everywhere systems are eventually consistent: waiting for a job status to flip to `done`, for a file to appear, for a deploy to roll out. This snippet walks from a basic fixed-interval poller to one with a deadline, then to exponential backoff with jitter so a thundering herd does not hammer the upstream. Reach for it any time you need to wait for a remote condition without writing the same retry loop again.
Fetch with Async/Await Recipes
The browser and Node 22+ both ship `fetch`, but the easy-to-miss details (`response.ok`, content-type parsing, body shape on POST, parallel error isolation) are exactly where bugs hide. This snippet collects four recipes built on `async`/`await` and a mocked `fetch` so each example runs end-to-end. Use it as the baseline for code that talks to JSON APIs without reaching for axios or a wrapper library.
Question Banks
Promises and async/await Basics
Beginner drills on Promise resolution order, async/await semantics, and the microtask queue. Three short JavaScript snippets you can predict line-by-line.
JavaScript Promise, async/await, and Event Loop Traces
Six traces emphasizing microtask vs macrotask ordering, `Promise.all` timing, `await`-as-microtask sequencing, and the classic `var` + `setTimeout` loop pitfall.
Fetch API and Error Handling Quiz
Practice the small but easily-bungled `fetch` rituals: real error handling, Promise wrappers around timers, and `Promise.resolve` / `Promise.reject` for branching success states.
Community
Promises, await, and the Microtask Queue
What a microtask actually is, why Promise.resolve().then never runs synchronously, how await schedules continuations as microtasks, and the four-column trace I run when ordering surprises me.
The JavaScript Event Loop: Tasks, Microtasks, and Rendering
A trace-by-hand walkthrough of the event loop: pick a macrotask, drain microtasks to empty, then optionally render. Worked example interleaves setTimeout, Promise, queueMicrotask, await, and requestAnimationFrame.
