Tweakr
    Preparing search index...

    Function memoizeAsync

    • Memoizes an asynchronous function by caching its resolved promises based on a deterministic key derived from its arguments.

      Supports deep object keys via stableStringify and allows a custom cache resolver for flexible key generation.

      Ensures that concurrent calls with the same arguments share the same in-flight promise.

      Type Parameters

      • T extends (...args: any[]) => Promise<any>

        The async function type to memoize.

      Parameters

      • fn: T

        The asynchronous function whose results should be cached.

      • Optionalresolver: (...args: Parameters<T>) => string

        Optional custom cache key resolver.

      Returns (...args: Parameters<T>) => Promise<ReturnType<T>>

      A memoized async function returning cached or pending results.

      const fetchUser = memoizeAsync(async (id: number) => {
      console.log("Fetching user:", id);
      return { id, name: "User" + id };
      });

      await fetchUser(1); // Executes
      await fetchUser(1); // Returns cached promise
      // Custom cache resolver
      const fetchByObject = memoizeAsync(
      async (user: { id: number }) => ({ ...user, fetched: true }),
      (user) => String(user.id)
      );
      await fetchByObject({ id: 5 }); // Computed
      await fetchByObject({ id: 5 }); // Cached via resolver

      1.2.0