• Create a Promise-returning Function that returns the memoized results of a Promise. The key for the lookup cache is determined by the keyExtractor Function.

    An optional Map instance can be provided to be used as cache. This allows for example to prepopulate the cache, or to force recomputation of some values by removing their corresponding keys. If no instance is provided an empty Map will be created.

    Remarks

    If the Promise throws an error, no result will be cached and the Promise will be run again next time.

    Example

    Memoize the fetch function

    const keyExtractor = (url) => url;

    const memoizedFetch = memoizePromise(fetch, keyExtractor);

    const result1 = memoizedFetch("https://...");
    const result2 = memoizedFetch("https://...");
    // fetch will only be called once

    Example

    Provide an initial cache restored from database

    const restoredCacheFromDatabase = new Map([["https://...", 1]]);

    const keyExtractor = (url) => url;

    const memoizedFetch = memoizePromise(fetch, keyExtractor, restoredCacheFromDatabase);

    const result = memoizedFetch("https://...");
    // result will be directly returned from cache

    Example

    Clear cache after 5 seconds

    const cache = new Map();
    const keyExtractor = (url) => url;

    const memoizedFetch = memoizePromise(fetch, keyExtractor, cache);

    // ... fill the cache

    setTimeout(() => {
    cache.clear();
    }, 5000);

    Returns

    the memoized result

    Type Parameters

    • TArgs extends unknown[]

    • R

    Parameters

    • fn: ((...args: TArgs) => PromiseLike<R>)

      the Function to memoize

    • keyExtractor: ((...args: TArgs) => unknown)

      the Function to extract the key for the cache

        • (...args: TArgs): unknown
        • Parameters

          • Rest ...args: TArgs

          Returns unknown

    • cache: Map<unknown, R> = ...

      an optional, possibly prefilled Map instance to use as cache

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

      • (...args: TArgs): Promise<R>
      • Parameters

        • Rest ...args: TArgs

        Returns Promise<R>

Generated using TypeDoc