@pengzhanbo/utils - v3.4.1
    Preparing search index...

    Function withTimeout

    • Executes an async function and enforces a timeout.

      执行异步函数, 超时则强制拒绝

      Type Parameters

      • T

      Parameters

      • run: () => Promise<T>

        the async function to execute.

      • ms: number

        the number of milliseconds to wait before rejecting the promise.

      Returns Promise<T>

      A promise that resolves with the result of the async function, or rejects with a TimeoutError if the function does not resolve within the specified timeout. 一个 promise,它将解析为异步函数的结果,或者如果在指定超时内函数未解析,则拒绝并抛出TimeoutError

      async function fetchData() {
      const response = await fetch('https://example.com/data');
      return response.json();
      }

      try {
      const data = await withTimeout(fetchData, 1000);
      console.log(data); // Logs the fetched data if `fetchData` is resolved within 1 second.
      } catch (error) {
      console.error(error); // Will log 'TimeoutError' if `fetchData` is not resolved within 1 second.
      }