可以使用async/await和Promise.race来实现一个可指定超时时间的异步函数重试机制,具体代码如下:
async function retryWithTimeout(fn, maxAttempts, delay, timeout) {
let attempt = 0;
while (attempt < maxAttempts) {
try {
const result = await Promise.race([fn(), timeoutPromise(timeout)]);
return result;
} catch (error) {
console.error(`Attempt #${attempt + 1} failed with error: ${error.message}`);
attempt++;
if (attempt === maxAttempts) {
throw error;
}
await delayPromise(delay);
}
}
}
function timeoutPromise(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Timeout'));
}, timeout);
});
}
function delayPromise(delay) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, delay);
});
}
使用时,传入一个需要重试的异步函数fn、最大重试次数maxAttempts、每次重试的延迟时间delay和超时时间timeout。其中timeoutPromise和delayPromise分别返回一个设置了超时和延迟的Promise,retryWithTimeout函数在每次重试时等待delayPromise返回的Promise,如果fn在timeout时间内未返回结果,则返回timeoutPromise返回的Promise。重试次数达到maxAttempts时,抛出错误。