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

    Function retry

    • Retry a async function with a delay

      重试异步函数并设置延迟

      Type Parameters

      • T

        The type of the resolved value / 解析值的类型

      Parameters

      • fn: (signal?: AbortSignal) => Promise<T>

        the function to retry / 重试的异步函数

      • options: RetryOptions = {}

        the options for retry / 重试选项

        • Optionaldelay?: number

          The delay between retries, default is 0

          重试间隔,默认为 0

        • Optionallimit?: number

          The total number of attempts (including the initial call), default is 3

          总尝试次数(包含初始调用),默认 3

        • Optionalsignal?: AbortSignal

          AbortSignal for cancellation. When aborted, the retry will be rejected with AbortError.

          用于取消的 AbortSignal。当触发中止时,重试将被拒绝并返回 AbortError。

        • Optionaltimeout?: number

          Maximum total time in milliseconds for all retries. If exceeded, the retry will be rejected with TimeoutError.

          所有重试的最大总时间(毫秒)。如果超过此时间,重试将被拒绝并返回 TimeoutError。

      Returns RetryablePromise<T>

      const result = await retry(async () => {
      return await fetch('https://example.com').then((res) => res.json())
      }, { limit: 3, delay: 1000 })

      With cancellation / 带取消功能

      const controller = new AbortController()
      const promise = retry(fetchData, { signal: controller.signal })

      // Cancel the retry / 取消重试
      controller.abort()

      With timeout / 带超时限制

      try {
      const result = await retry(fetchData, { limit: 5, timeout: 10000 })
      } catch (error) {
      if (error instanceof TimeoutError) {
      console.log('Retry timed out after 10 seconds')
      }
      }