Tweakr
    Preparing search index...

    Function onceNAsync

    • Runs an async function at most n times. Subsequent calls return the result of the last invocation.

      The returned function caches the result of each invocation and ensures fn is called no more than n times. After n calls, the cached result is returned.

      Type Parameters

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

        The type of the async function to be invoked.

      Parameters

      • n: number

        The maximum number of times to call fn.

      • fn: T

        The async function to invoke.

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

      A function that calls fn up to n times and returns a Promise of the result.

      1.2.0

      const limited = onceNAsync(2, async () => {
      console.log("Running");
      return 42;
      });
      await limited(); // logs "Running", returns 42
      await limited(); // logs "Running", returns 42
      await limited(); // returns 42, does not log