@jiminp/tooltool
    Preparing search index...

    Function cached

    • Creates a memoized async function that deduplicates in-flight requests and caches results.

      Subsequent calls with the same cache key receive the original promise (request coalescing). If the promise rejects, the entry is evicted so the next call can retry.

      Type Parameters

      • ArgsType extends unknown[]

        Tuple of the function's parameter types.

      • T

        The resolved return type.

      • K = unknown

        The cache key type.

      Parameters

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

        The async function to memoize.

      • OptionalkeyGenerator: (...args: ArgsType) => K

        Derives a cache key from arguments. Defaults to JSON.stringify(args).

      Returns CachedFunction<ArgsType, T>

      A CachedFunction with an additional .clearCache() method.

      Rejections are not cached. To cache negative results, resolve with Result<T, E> or null. Default keys use JSON serialization, not object identity or deep equality: property order can distinguish equivalent objects, while undefined, functions, symbols, and nonfinite numbers can collide with omitted properties or null. Cycles and bigint values can throw during key generation. Supply a custom key generator when these distinctions matter; its keys use Map equality. Fulfilled entries remain until cleared. Clearing does not cancel in-flight calls, and an older rejection cannot evict a newer entry created after clearing.

      const cachedFetch = cached(async (id: string) => fetch(`/users/${id}`).then(r => r.json()));
      await cachedFetch("42"); // executes fetch
      await cachedFetch("42"); // returns cached promise
      cachedFetch.clearCache();