Tweakr
    Preparing search index...

    Function onceAsync

    • Ensures an asynchronous function is executed only once.

      Subsequent calls return the same pending or resolved promise from the first invocation.

      Type Parameters

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

        The async function type.

      Parameters

      • fn: T

        The asynchronous function to execute only once.

      Returns (
          this: ThisParameterType<T>,
          ...args: Parameters<T>,
      ) => Promise<Awaited<ReturnType<T>>>

      A wrapped function that runs fn once and caches the promise.

      const init = onceAsync(async () => {
      console.log("Initializing...");
      await new Promise(r => setTimeout(r, 1000));
      return "ready";
      });

      await init(); // Logs "Initializing..."
      await init(); // Returns cached promise, no log

      1.2.0