Skip to content

MustafaKucukcoskun/Refine-agent-kit / .agents/skills/async-javascript-patterns

async-javascript-patterns

Unverified

Async JavaScript/TypeScript Patterns

Correct async is harder than it looks. Every pattern here exists because the naive version burns production.

When to Use vs. Related Skills

You want to…Use
Async JS/TS patternsasync-javascript-patterns (this)
Async Python (asyncio)async-python-patterns
Rate limiting / retrythis + error-handling-patterns
Worker threads, streamsthis (streams section)
General JS qualitynodejs-best-practices

1. Promise Composition — Choose the Right Primitive

You want…UseFails if
All complete, fail fastPromise.allAny rejects → whole thing rejects
All complete, collect successes AND failuresPromise.allSettledNever rejects; inspect each result
First success, ignore losersPromise.anyAll reject → AggregateError
First to settle (success OR failure)Promise.raceWhichever settles first wins
// Fan-out with partial failure tolerance
const results = await Promise.allSettled(urls.map(fetchJson));
const ok = results.filter((r): r is PromiseFulfilledResult<User> => r.status === "fulfilled");
const failed = results.filter((r) => r.status === "rejected");
log.warn({ failed: failed.length }, "some fetches failed");
return ok.map((r) => r.value);

2. Cancellation with AbortController

Long-running fetches MUST be cancellable. Browsers, React effects, and Node servers all need this.

// Request with timeout
export async function fetchWithTimeout(url: string, ms = 5000): Promise<Response> {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(new Error("timeout")), ms);
  try {
    return await fetch(url, { signal: ctrl.signal });
  } finally {
    clearTimeout(timer);
  }
}

// React effect with cleanup
useEffect(() => {
  const ctrl = new AbortController();
  fetch("/api/data", { signal: ctrl.signal })
    .then((r) => r.json())
    .then(setData)
    .catch((e) => {
      if (e.name !== "AbortError") throw e;
    });
  return () => ctrl.abort();
}, []);

3. Concurrency Limits (avoid unbounded fan-out)

Promise.all(items.map(slow)) with 10,000 items = 10,000 concurrent requests = death.

// Hand-rolled concurrency limiter (no dep)
export async function pLimit<T, R>(
  items: T[],
  limit: number,
  worker: (item: T) => Promise<R>,
): Promise<R[]> {
  const out: R[] = new Array(items.length);
  let i = 0;
  async function run() {
    while (i < items.length) {
      const idx = i++;
      out[idx] = await worker(items[idx]);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run));
  return out;
}

// Usage
const users = await pLimit(userIds, 10, fetchUser);

Production alternatives: p-limit, p-map, p-queue (npm).

4. Error Propagation — Top 3 Bugs

Bug: Unhandled rejection from fire-and-forget

// ❌ no .catch → Node crashes or browser logs unhandled rejection
doBackground();

// ✅
doBackground().catch((e) => log.error({ err: e }, "background failed"));

Bug: Errors lost inside .forEach

// ❌ forEach ignores async callbacks
items.forEach(async (x) => await save(x)); // fires in parallel, ignores errors

// ✅
for (const x of items) await save(x); // sequential
// OR
await Promise.all(items.map(save)); // parallel

Bug: Rethrowing drops stack trace (pre-ES2022)

// ✅ ES2022+: preserve cause
try {
  await risky();
} catch (e) {
  throw new Error("save failed", { cause: e });
}

5. Race Condition: Stale Response

// ❌ old request response may overwrite newer state
function search(q: string) {
  fetch(`/api/search?q=${q}`).then((r) => r.json()).then(setResults);
}

// ✅ track latest, ignore stale
let latest = 0;
function search(q: string) {
  const me = ++latest;
  fetch(`/api/search?q=${q}`).then((r) => r.json()).then((d) => {
    if (me === latest) setResults(d);
  });
}

6. async Without await = Hidden Bug

// ❌ function marked async but no await — wraps return in Promise needlessly
async function getName() { return user.name; }

// ✅ if no async work, don't mark async
function getName() { return user.name; }

7. Streams Over await response.json() for Large Payloads

// Process large NDJSON without loading all in memory
const res = await fetch("/api/export");
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
let buf = "";
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buf += value;
  const lines = buf.split("\n");
  buf = lines.pop()!;
  for (const line of lines) if (line) process(JSON.parse(line));
}

8. Retry with Exponential Backoff

export async function retry<T>(
  fn: () => Promise<T>,
  { maxAttempts = 3, baseMs = 200, maxMs = 5000 } = {},
): Promise<T> {
  let lastErr: unknown;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (e) {
      lastErr = e;
      if (attempt === maxAttempts) break;
      const ms = Math.min(baseMs * 2 ** (attempt - 1), maxMs);
      await new Promise((r) => setTimeout(r, ms + Math.random() * ms));
    }
  }
  throw lastErr;
}

Anti-Patterns

Anti-patternWhy badFix
new Promise((res) => { result = await x; res(result); })new Promise + async is always a bugJust return x
Promise.all(items.map(async (x) => { ... })) with no limitUnbounded concurrencyUse concurrency limiter
try { ... } catch (e) { console.log(e); }Swallows, can't recover upstreamLog AND rethrow, or handle properly
await in .forEachforEach doesn't waitUse for...of or Promise.all
Not passing signal to fetchCan't cancelAlways pass AbortSignal
Mutating shared state inside parallel tasksRace conditionUse local state, aggregate at end

Pre-Commit Checklist

  • Every async function has at least one await (or returns a Promise)
  • Every fire-and-forget promise has .catch
  • No unbounded Promise.all over user-supplied arrays
  • Long-running fetches pass AbortSignal
  • No shared-state mutation inside parallel tasks
  • Sequential loops use for...of, not .forEach with async

Related Skills

  • error-handling-patterns — retry, fallback, circuit breaker
  • nodejs-best-practices — Node-specific async
  • react-best-practices — effect cleanup, stale closures
  • systematic-debugging — when async misbehaves
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 196kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 192kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 192kUpdated Claude CodeCodexVerifiedInstall