41 lines
944 B
JavaScript
41 lines
944 B
JavaScript
// 简单 sleep 工具,供重试间隔等待使用。
|
|
export function sleep(ms) {
|
|
return new Promise((resolve) => {
|
|
setTimeout(resolve, ms)
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 通用重试执行器。
|
|
* @param {(retryIndex:number)=>Promise<any>} fn 被执行函数
|
|
* @param {object} options
|
|
* @param {number} options.retries 失败后最大重试次数
|
|
* @param {number} options.delay 每次重试前等待毫秒
|
|
* @param {(error:any,retryIndex:number)=>boolean} options.shouldRetry 是否重试
|
|
*/
|
|
export async function runWithRetry(fn, options = {}) {
|
|
const {
|
|
retries = 2,
|
|
delay = 500,
|
|
shouldRetry = () => true
|
|
} = options
|
|
|
|
let lastError = null
|
|
|
|
for (let index = 0; index <= retries; index += 1) {
|
|
try {
|
|
return await fn(index)
|
|
} catch (error) {
|
|
lastError = error
|
|
|
|
if (index >= retries || !shouldRetry(error, index)) {
|
|
throw error
|
|
}
|
|
|
|
await sleep(delay)
|
|
}
|
|
}
|
|
|
|
throw lastError
|
|
}
|