Asynchronous Programming
async-programming
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.
Cancellable fetch with AbortController
Every modern UI eventually needs to cancel in-flight requests: a search box that fires on every keystroke, a route change that abandons a partially loaded page, a tab close that should free sockets. `AbortController` is the standard primitive for this. This snippet covers the minimal abort pattern, a `fetchWithTimeout` helper that aborts on a deadline, and a hook-friendly cleanup pattern that pairs each request with its own controller.
Async Queue with Concurrency Limit
When you have hundreds of API calls but the upstream caps you at 5 in flight, naive `Promise.all` is a 429 storm waiting to happen. A concurrency-limited queue runs at most `n` tasks at once, draining a backlog as workers free up. This snippet starts with the minimal worker pool, adds per-task error isolation, then layers in cancellation and ordered results so the helper holds up in production.
Async Batch Processor
High-volume event streams (analytics, logs, telemetry) are usually best forwarded in batches: batching lowers per-call overhead, plays nicely with bulk endpoints, and lets you compress traffic. The trick is choosing when to flush. This snippet builds a processor that flushes whenever the buffer hits a max size OR a max wait elapses, then layers in flush-on-demand and graceful shutdown so nothing is lost during process exit.
CompletableFuture for Async Workflows
`CompletableFuture` is Java's promise-style API for composing async work. This snippet covers `supplyAsync` to start a task, `thenApply` for synchronous transforms, `thenCompose` for chaining another async step, and `allOf` to fan out parallel tasks. Use it for any workflow that mixes I/O calls or CPU work without blocking the calling thread.
