Skip to content
jshacks.dev
Async

Async Utilities Worth Having in Every Codebase

Eight small async helpers worth keeping in a shared module, including sleep, timeout, retry, pool, deferred and memoize, each with code and its output.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ, Apache Kafka and Redis logos.

Every JavaScript codebase that does real work ends up writing the same small async helpers, usually several times in slightly different forms. One service has a sleep, another has a wait, a third has a delay that takes seconds, not milliseconds. Collecting a handful in one shared module, with tests, removes that drift and makes the behavior consistent across the project. This post lists eight helpers worth having, each short enough to read in a minute, written for Node.js 24 with the output shown. They use only the platform, no libraries. Keep the module small: a utility earns its place by being needed in more than two files and by being easy to get subtly wrong.

1. sleep

The smallest and most common. It takes a duration and optionally an AbortSignal, so a pending sleep can be cancelled.

utils.mjsJavaScript
export function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const id = setTimeout(resolve, ms);
    signal?.addEventListener(
      "abort",
      () => {
        clearTimeout(id);
        reject(signal.reason);
      },
      { once: true }
    );
  });
}

Node.js also ships timers/promises, whose setTimeout(ms) is a promise-based sleep with signal support, and it is a fine choice. Wrapping it under your own name keeps call sites short and lets you swap the implementation in tests.

2. withTimeout

Race a promise against a timer, and clear the timer when the work finishes, so the process is not held open.

with-timeout.mjsJavaScript
import { sleep } from "./utils.mjs";

export function withTimeout(promise, ms, message = `timed out after ${ms} ms`) {
  let id;
  const timeout = new Promise((_, reject) => {
    id = setTimeout(() => reject(new Error(message)), ms);
  });
  return Promise.race([promise, timeout]).finally(() => clearTimeout(id));
}

try {
  await withTimeout(sleep(200), 50);
} catch (error) {
  console.log(error.message);
}
console.log(await withTimeout(sleep(10).then(() => "fast"), 50));
Text
timed out after 50 ms
fast

This does not cancel the underlying work, so pass an AbortSignal into the work as well when it supports one.

3. retry

Retry with exponential backoff and a cap on attempts, rethrowing the last error.

retry.mjsJavaScript
import { sleep } from "./utils.mjs";

export async function retry(fn, { attempts = 3, baseMs = 10 } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await fn(attempt);
    } catch (error) {
      lastError = error;
      if (attempt < attempts) await sleep(baseMs * 2 ** (attempt - 1));
    }
  }
  throw lastError;
}

const result = await retry(async (attempt) => {
  if (attempt < 3) throw new Error(`attempt ${attempt} failed`);
  return `ok on attempt ${attempt}`;
});
console.log(result);
Text
ok on attempt 3

A production version adds jitter and a predicate that decides which errors are worth retrying, as covered in retrying a failed promise with backoff.

4. mapLimit

Map over a list with a concurrency cap and results in input order, using a pool of workers that pull from a shared index.

map-limit.mjsJavaScript
export async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  const worker = async () => {
    while (next < items.length) {
      const index = next++;
      results[index] = await fn(items[index], index);
    }
  };
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

console.log(await mapLimit([1, 2, 3, 4], 2, async (n) => n * n));
Text
[ 1, 4, 9, 16 ]

5. deferred

A promise with its resolve and reject exposed. Node.js 24 has Promise.withResolvers(), which does exactly this, so a helper is only needed for older runtimes.

deferred.mjsJavaScript
const { promise, resolve } = Promise.withResolvers();
setTimeout(() => resolve("resolved from outside"), 10);
console.log(await promise);
Text
resolved from outside

Use it to bridge an event into a promise, and see using Promise.withResolvers to wrap an event for patterns.

6. memoizeAsync

Cache the promise, not the value, so concurrent callers share one in-flight request and failures are not cached forever.

memoize.mjsJavaScript
export function memoizeAsync(fn) {
  const cache = new Map();
  return (key) => {
    if (!cache.has(key)) {
      const promise = fn(key).catch((error) => {
        cache.delete(key);
        throw error;
      });
      cache.set(key, promise);
    }
    return cache.get(key);
  };
}

let calls = 0;
const load = memoizeAsync(async (id) => {
  calls++;
  return `user ${id}`;
});

console.log(await Promise.all([load(1), load(1), load(2)]));
console.log("underlying calls:", calls);
Text
[ 'user 1', 'user 1', 'user 2' ]
underlying calls: 2

Two simultaneous requests for key 1 caused one call. Add an expiry if the data can change, since this cache never forgets a successful value.

7. settleAll

A thin wrapper around Promise.allSettled that splits results into values and errors, so callers do not repeat the same filter code.

settle.mjsJavaScript
export async function settleAll(promises) {
  const results = await Promise.allSettled(promises);
  return {
    values: results.filter((r) => r.status === "fulfilled").map((r) => r.value),
    errors: results.filter((r) => r.status === "rejected").map((r) => r.reason),
  };
}

const { values, errors } = await settleAll([Promise.resolve(1), Promise.reject(new Error("no")), Promise.resolve(3)]);
console.log(values, errors.map((e) => e.message));
Text
[ 1, 3 ] [ 'no' ]

8. onceAsync

Make sure an initialization function runs once, even when many callers ask at the same time, such as opening a database connection lazily.

once.mjsJavaScript
export function onceAsync(fn) {
  let promise;
  return () => (promise ??= fn());
}

let opened = 0;
const getConnection = onceAsync(async () => {
  opened++;
  return { id: opened };
});

const [a, b] = await Promise.all([getConnection(), getConnection()]);
console.log(a === b, "opened:", opened);
Text
true opened: 1

If initialization can fail and you want a retry on the next call, clear the cached promise in a catch, as memoizeAsync does.

Keeping the module healthy

A shared utilities module rots if nobody owns it. Give it tests, which are easy here since every helper is a pure function over promises and timers, and use the built-in test runner's fake timers for the time-based ones. Document each helper with its failure behavior: does it cancel the work, does it clear its timers, does it keep the error type? And resist adding to it. A helper used once belongs next to its caller, and a helper that grows five options belongs in a library, such as p-limit or p-retry, whose authors have already handled the edge cases.

Where the advice stops

These helpers cover the common cases and not all of them. They do not persist state, they do not coordinate across processes, and the retry and withTimeout versions here ignore cancellation of the underlying work. If your project needs those, adopt a maintained library instead of growing your own. The aim is a small shared vocabulary, not a framework.

Testing the helpers

These functions are small, which makes them cheap to test, and they are worth testing because their bugs are subtle. A timeout helper that forgets to clear its timer passes every functional test and then keeps the test process alive for the length of the timeout, which you notice as a test runner that hangs on exit. A retry helper that retries on the final attempt, or sleeps after it, passes the happy path and slows every failing call. A memoizer that caches rejected promises passes until the first transient error, then returns that error forever.

Write one test per behavior that matters. For withTimeout: it resolves with the value when the work is fast, rejects with the timeout message when it is slow, and leaves no active timers behind. For retry: it returns the first success, makes exactly the configured number of attempts on persistent failure and rethrows the last error, not the first. For memoizeAsync: concurrent calls share one invocation, a failure is not cached and a later call tries again. The built-in node:test runner and its mock timers are enough, and no extra dependency is needed.

Naming and signatures

Consistency across the helpers matters more than the choice of names. Take durations in milliseconds everywhere, because setTimeout does, and a helper that takes seconds will be misused within a month. Accept an options object as the last argument and put signal in it, following the convention of the platform APIs, so a caller who knows fetch already knows how to cancel your helper. Return promises, not callbacks, and throw real Error objects so stack traces and instanceof checks work. If a helper rejects with a timeout, use a recognizable error name, for example TimeoutError, so callers can tell a timeout from other failures without matching on message text.

Typing them in TypeScript

If the codebase uses TypeScript, the helpers should keep type information through the call. A mapLimit<T, R>(items: T[], limit: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> signature lets the result type follow the callback, and a generic withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> returns the same type as its input. Typed helpers catch the mistake of passing a function where a promise is expected, which is a common slip with withTimeout(fn, 100) instead of withTimeout(fn(), 100).

Also inPatterns
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.