m2pool_backend_app/public/retry.js

33 lines
955 B
JavaScript
Raw Permalink Normal View History

2025-04-10 10:53:16 +00:00
/**
* 异步任务重试器
* @param {Function} task 异步任务
* @param {Number} maxRetries 最大重试次数
* @param {Number} delay 重试间隔
* @returns
*/
async function executeWithRetry(task, maxRetries, delay) {
let attempts = 0;
while (attempts < maxRetries) {
try {
// 尝试执行异步任务
const result = await task();
// console.log("任务成功");
return result; // 成功时返回结果
} catch (error) {
attempts++;
console.error(`尝试 ${attempts} 失败:`, error.message);
if (attempts >= maxRetries) {
console.error("已达最大重试次数,任务失败。");
throw error; // 达到最大重试次数时抛出错误
}
console.log(`等待 ${delay} 秒后重试...`);
// 等待指定时间后再重试
await new Promise((resolve) => setTimeout(resolve, delay * 1000));
}
}
}
module.exports = executeWithRetry