Tweakr
    Preparing search index...

    Function withTimeout

    • Wraps an asynchronous function with a timeout.

      If the wrapped function does not resolve or reject within the specified time, the returned promise rejects with a "Timeout" error.

      Type Parameters

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

        The type of the async function.

      Parameters

      • fn: T

        The asynchronous function to wrap.

      • ms: number

        Timeout duration in milliseconds.

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

      A new function that returns a promise which rejects if the timeout is exceeded.

      const fetchData = async () => {
      await new Promise(r => setTimeout(r, 2000));
      return "Done";
      };

      const result = withTimeout(fetchData, 1000)();
      result.catch(err => console.log(err.message)); // "Timeout"

      1.1.0