当前位置: 首页 > news >正文

《优雅应对失败:JavaScript异步重试模式详解》

一个函数解决90%的异步请求稳定性问题

 * 异步重试函数* @param {Function} asyncFn - 要执行的异步函数* @param {number} maxRetries - 最大重试次数(包括首次调用)* @param {number} retryInterval - 重试间隔(毫秒)* @returns {Promise<any>} - 返回异步函数的结果或抛出错误*/
async function retryAsync(asyncFn, maxRetries = 3, retryInterval = 1000) {// 验证参数if (typeof asyncFn !== 'function') {throw new TypeError('第一个参数必须是函数');}if (!Number.isInteger(maxRetries) || maxRetries < 1) {throw new TypeError('最大重试次数必须是正整数');}if (!Number.isInteger(retryInterval) || retryInterval < 0) {throw new TypeError('重试间隔必须是非负整数');}let lastError;for (let attempt = 1; attempt <= maxRetries; attempt++) {try {// 尝试执行异步函数const result = await asyncFn();console.log(`第 ${attempt} 次尝试成功`);return result;} catch (error) {lastError = error;console.warn(`第 ${attempt} 次尝试失败: ${error.message}`);// 如果是最后一次尝试,不再等待if (attempt === maxRetries) {console.error(`已达到最大重试次数 (${maxRetries}),操作失败`);break;}// 等待指定间隔后重试console.log(`等待 ${retryInterval}ms 后重试...`);await sleep(retryInterval);}}// 所有尝试都失败,抛出最后的错误throw lastError;
}/*** 睡眠函数,用于等待指定时间* @param {number} ms - 等待的毫秒数* @returns {Promise<void>}*/
function sleep(ms) {return new Promise(resolve => setTimeout(resolve, ms));
}// 使用示例
async function exampleUsage() {// 模拟一个可能失败的异步函数let callCount = 0;const unreliableAsyncFunction = async () => {callCount++;console.log(`调用异步函数,第 ${callCount} 次`);// 模拟失败:前两次失败,第三次成功if (callCount < 3) {throw new Error(`模拟失败,第 ${callCount} 次调用`);}return { success: true, data: '这是返回的数据', callCount };};try {// 尝试最多5次,每次间隔2秒const result = await retryAsync(unreliableAsyncFunction, 5, 2000);console.log('最终成功:', result);return result;} catch (error) {console.error('最终失败:', error.message);throw error;}
}// 测试
exampleUsage().catch(() => {console.log('主流程捕获到错误');
});// 更简洁的版本(去掉日志和参数验证)
async function retryAsyncSimple(asyncFn, maxRetries = 3, retryInterval = 1000) {let lastError;for (let attempt = 1; attempt <= maxRetries; attempt++) {try {return await asyncFn();} catch (error) {lastError = error;if (attempt === maxRetries) break;if (retryInterval > 0) {await new Promise(resolve => setTimeout(resolve, retryInterval));}}}throw lastError;
}// 支持指数退避策略的版本
async function retryAsyncWithBackoff(asyncFn, maxRetries = 3, baseInterval = 1000,maxInterval = 10000
) {let lastError;for (let attempt = 1; attempt <= maxRetries; attempt++) {try {return await asyncFn();} catch (error) {lastError = error;if (attempt === maxRetries) break;// 指数退避:等待时间逐渐增加const delay = Math.min(baseInterval * Math.pow(2, attempt - 1),maxInterval);await new Promise(resolve => setTimeout(resolve, delay));}}throw lastError;
}// 导出函数(如果是模块环境)
// export { retryAsync, retryAsyncSimple, retryAsyncWithBackoff };```
http://www.jsqmd.com/news/288879/

相关文章:

  • 交易·社交·管理一体化,开源可商用的二手平台小程序源码系统
  • 基于PLC的室内温度控制系统设计(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • Docker run 命令详解(-a、-d、-e、-h、-i、-m、-p、-t、-v、--cpuset、--dns、--env-file、--expose、--link、--name、--net)
  • 全网最全9个AI论文平台,专科生轻松搞定论文写作!
  • 2026必备!专科生毕业论文AI论文工具TOP8测评
  • 哈希表电话号码管理系统(设计源文件+万字报告+讲解)(支持资料、图片参考_相关定制)_文章底部可以扫码
  • 把PP-OCRv5_server模型转换为OpenVINO格式
  • 基于Docker部署M3U8流媒体
  • 国外的文献资料在哪里查?实用查询途径与方法指南
  • 华为光学工程师面试题
  • AI媒体助理软件批量文章生成设置教程
  • 【实战项目】 基于BP神经网络的情感机器人玩具的设计与实现
  • 机械制造领域网页,JAVA如何实现大文件的分块与秒传?
  • 2026铝镁锰/铝镁锰板/铝镁锰合金屋面/金属屋面板厂家推荐,专业施工品质保障!
  • 国外期刊论文搜索网站使用指南:高效查找学术资源的实用平台
  • 写论文找不到外国文献?方法合集来了!——轻松获取国外文献的实用技巧分享
  • BLDC直流无刷电机控制方案 采用R5F0C807控制,通过3三路具有中断触发功能的输入端口采...
  • 刷机固件是【当贝桌面4.0】误认为卡启动界面无法进入系统操作说明
  • 外文文献查找的6个途径及相关方法指南
  • 外文文献去哪里找?这几大渠道别再错过了——实用查找渠道分享
  • 2026汽车AI市场分析榜单原圈科技揭示决胜未来的秘诀
  • 如何查找国外期刊 国外期刊怎么找 国外期刊查找方法指南
  • 为什么程序员,越来越排斥面试时做题?
  • 原圈科技AI市场分析让客户需求“说“出来,赢在2026!
  • 从夯到拉,锐评13个JavaWeb框架
  • 互联网大厂Java求职面试实战:Spring Boot、微服务与AI技术全方位解析
  • 手绘贴图画断手?“AI 炼金术”3分钟量产风格化材质
  • 使用 LoRA 进行大模型微调:原理、实现与效果评估
  • 恒压供水项目:西门子PLC实现高效一拖多控制
  • 告别费眼费嗓!easyVoice让文字开口说话,内网限制?cpolar一招破解