@supuwoerc/toolkit
    Preparing search index...

    Function retry

    • 重试执行异步函数,支持指数退避策略 Retry an asynchronous function with exponential backoff support

      Type Parameters

      • T

        函数返回的 Promise 类型 / The Promise type returned by the function

      Parameters

      • fn: () => Promise<T>

        需要重试的异步函数 / The asynchronous function to retry

      • options: {
            backoffFactor?: number;
            delayMs?: number;
            maxAttempts?: number;
            shouldRetry?: (error: unknown, attempt: number) => boolean;
        } = {}

        重试配置选项 / Retry configuration options

        • OptionalbackoffFactor?: number

          退避因子,每次重试延迟时间乘以此值 / Backoff factor, delay multiplies by this each retry

        • OptionaldelayMs?: number

          初始延迟时间(毫秒) / Initial delay in milliseconds

        • OptionalmaxAttempts?: number

          最大尝试次数 / Maximum number of attempts

        • OptionalshouldRetry?: (error: unknown, attempt: number) => boolean

          判断是否应该重试的函数 / Function to determine if should retry

      Returns Promise<T>

      成功执行的结果 / Successfully executed result

      最后一次尝试的错误或达到最大重试次数时的错误 / Last attempt error or error when max retries reached

      // 基本用法 / Basic usage
      const result = await retry(() => fetchData());
      // 自定义配置 / Custom configuration
      const result = await retry(() => apiCall(), {
      maxAttempts: 5,
      delayMs: 500,
      backoffFactor: 1.5,
      shouldRetry: (error, attempt) => error.status !== 404
      });