Libraries
    Preparing search index...
    • Wraps an async function so that concurrent calls with the same key share a single in-flight promise instead of starting duplicate operations.

      Once the shared promise resolves (or rejects), subsequent calls will start a new operation.

      Type Parameters

      • TArgs extends any[]

        The argument types of the wrapped function.

      • T

        The return type of the wrapped function.

      Parameters

      • keyFn: (...args: TArgs) => string

        A function that computes a cache key from the arguments. Calls with the same key will be deduplicated.

      • fn: (...args: TArgs) => Promise<T>

        The async function to wrap.

      Returns (...args: TArgs) => Promise<T>

      A deduplicated version of fn.

      import { dedupe } from '@cleverbrush/async';

      const fetchUser = dedupe(
      (id: number) => `user-${id}`,
      (id: number) => fetch(`/api/users/${id}`).then(r => r.json())
      );

      // These two calls share a single fetch:
      const [a, b] = await Promise.all([fetchUser(1), fetchUser(1)]);