@jiminp/tooltool
    Preparing search index...

    Function cached

    • Creates a memoized version of an asynchronous function to deduplicate requests and cache results.

      The wrapper stores the Promise keyed by the provided arguments. Any subsequent call with the same cache key receives the original promise, preventing duplicate work while the result is pending (request coalescing) and after it resolves.

      If the promise rejects, the cache entry is removed immediately so the next invocation can retry.

      Type Parameters

      • ArgsType extends unknown[]
      • T
      • K = unknown

      Parameters

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

        The asynchronous function to memoize.

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

        Optional function to derive cache keys. When omitted, JSON.stringify(args) is used. Provide a specific generator if arguments are complex objects or non-serializable.

      Returns CachedFunction<ArgsType, T>

      A callable object that behaves like the original function but includes a .clearCache() method.

      Because this function evicts keys on rejection, it does not "cache failures" by default. If you wish to cache a negative result (e.g., "User Not Found" to prevent repeated lookup), ensure fn resolves with a Result<T, E> or null instead of rejecting.

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