Skip to content

Function: memoize()

memoize<T>(factory, options?): () => Promise<T>

Run a zero-argument factory once; later calls return the same result. The memoized function mirrors the factory’s sync / async nature: a sync factory yields a sync getter (() => T), an async / thenable factory yields a promise-returning getter (() => Promise<T>) whose concurrent callers share the one in-flight promise until it settles.

Errors are never cached: a sync factory that throws propagates the throw, and an async factory that rejects evicts the cached promise, so in both cases the next call retries. Pass { ttlMs } to also expire and recompute a successful value after a window; without a TTL a success is cached forever.

For an async factory the TTL window starts when the promise resolves, not when it was created - a slow in-flight request never counts as already-expired, and concurrent callers keep sharing the one pending promise until it settles.

T

() => PromiseLike<T>

MemoizeOptions

() => Promise<T>

const ranges = functionModule.memoize(fetchIpRanges, { ttlMs: 24 * 60 * 60 * 1000 });
await ranges(); // fetches
await ranges(); // cached until 24h later

memoize<T>(factory, options?): () => T

Run a zero-argument factory once; later calls return the same result. The memoized function mirrors the factory’s sync / async nature: a sync factory yields a sync getter (() => T), an async / thenable factory yields a promise-returning getter (() => Promise<T>) whose concurrent callers share the one in-flight promise until it settles.

Errors are never cached: a sync factory that throws propagates the throw, and an async factory that rejects evicts the cached promise, so in both cases the next call retries. Pass { ttlMs } to also expire and recompute a successful value after a window; without a TTL a success is cached forever.

For an async factory the TTL window starts when the promise resolves, not when it was created - a slow in-flight request never counts as already-expired, and concurrent callers keep sharing the one pending promise until it settles.

T

() => T

MemoizeOptions

() => T

const ranges = functionModule.memoize(fetchIpRanges, { ttlMs: 24 * 60 * 60 * 1000 });
await ranges(); // fetches
await ranges(); // cached until 24h later