请求重试高阶函数是接收原始请求函数(如fetch或axios.get)并返回自动按策略重试的新函数;它具备通用性、可配置最大重试次数、退避延迟、失败判定条件及可取消性。

什么是请求重试高阶函数
它是一个接收原始请求函数(如 fetch 或 axios.get)作为参数,返回一个增强后的新函数——该函数在请求失败时自动按策略重试,无需每次手动写重试逻辑。
核心设计要点
通用性来自解耦:不绑定具体请求库、不硬编码 URL 或参数、不侵入业务错误处理逻辑。关键控制项包括:
- 最大重试次数
- 重试间隔(支持固定或指数退避)
- 失败判定条件(如仅对网络错误或特定状态码重试)
- 可取消性(避免重试已废弃的请求)
基础实现(支持 Promise 请求)
以下是一个轻量、无依赖的通用重试高阶函数:
const withRetry = (fn, options = {}) => {
const {
maxRetries = 3,
baseDelay = 1000,
shouldRetry = (error) => error?.name === 'TypeError' || (error?.response?.status >= 500),
} = options;
return async function retryWrapper(...args) {
let lastError;
for (let i = 0; i
try {
return await fn(...args);
} catch (err) {
lastError = err;
if (i === maxRetries || !shouldRetry(err)) {
throw err;
}
// 指数退避:1s, 2s, 4s...
await new Promise(r => setTimeout(r, baseDelay * Math.pow(2, i)));
}
}
throw lastError;
};
};
使用示例与适配技巧
✅ 直接包装 fetch:
const safeFetch = withRetry(fetch, { maxRetries: 2 });
safeFetch('/api/data').then(r => r.json()).catch(e => console.error(e));
✅ 包装 axios 方法(需确保返回 Promise):
立即学习“Java免费学习笔记(深入)”;
const safeGet = withRetry((url) => axios.get(url), {
shouldRetry: (err) => err?.response?.status === 429 || err?.code === 'ECONNABORTED'
});
✅ 支持 AbortSignal(结合浏览器原生取消):
在 fn(...args) 调用前注入 signal,或在 shouldRetry 中检查 err.name === 'AbortError' 并跳过重试。


















