当前位置:首页 > JavaScript

js retry 实现

2026-04-05 10:52:54JavaScript

实现 JavaScript 重试机制的方法

使用递归实现重试

递归方式适合处理异步操作,通过递归调用自身实现重试逻辑。示例代码:

function retryOperation(operation, maxRetries, delay) {
  return new Promise((resolve, reject) => {
    operation()
      .then(resolve)
      .catch(error => {
        if (maxRetries <= 0) {
          return reject(error);
        }
        setTimeout(() => {
          retryOperation(operation, maxRetries - 1, delay)
            .then(resolve)
            .catch(reject);
        }, delay);
      });
  });
}

使用循环实现重试

循环方式更直观,适合同步或异步操作。示例代码:

js retry 实现

async function retryOperation(operation, maxRetries, delay) {
  let lastError;
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw lastError;
}

带指数退避的重试

指数退避算法能有效避免资源竞争。示例代码:

async function retryWithBackoff(operation, maxRetries, initialDelay) {
  let delay = initialDelay;
  let lastError;

  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error;
      await new Promise(resolve => setTimeout(resolve, delay));
      delay *= 2; // 指数增加延迟时间
    }
  }
  throw lastError;
}

使用第三方库实现

现有库如async-retryp-retry提供成熟的重试机制。使用p-retry示例:

js retry 实现

const pRetry = require('p-retry');

async function run() {
  return pRetry(async () => {
    const result = await fetch('https://example.com');
    return result;
  }, {
    retries: 5,
    minTimeout: 1000
  });
}

重试策略定制

可根据需求定制重试条件,例如只对特定错误重试:

function shouldRetry(error) {
  return error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
}

async function retryWithCondition(operation, maxRetries) {
  let lastError;
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation();
    } catch (error) {
      if (!shouldRetry(error)) throw error;
      lastError = error;
    }
  }
  throw lastError;
}

取消重试机制

实现可取消的重试操作:

function retryWithCancel(operation, maxRetries, delay) {
  let cancel;
  const promise = new Promise(async (resolve, reject) => {
    let cancelled = false;
    cancel = () => { cancelled = true; };

    let lastError;
    for (let i = 0; i < maxRetries; i++) {
      if (cancelled) return reject(new Error('Cancelled'));
      try {
        return resolve(await operation());
      } catch (error) {
        lastError = error;
        await new Promise(r => setTimeout(r, delay));
      }
    }
    reject(lastError);
  });
  return { promise, cancel };
}

这些方法覆盖了从基础到高级的重试场景,可根据具体需求选择合适的实现方式。

标签: jsretry
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…

js实现截图

js实现截图

使用HTML2Canvas库实现截图 HTML2Canvas是一个流行的JavaScript库,可以将网页元素或整个页面转换为Canvas图像。安装方式: npm install html2canv…