You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.5 KiB
49 lines
1.5 KiB
|
|
export function retryAndRepeatRequest(requestFn, maxRetries = 3, retryDelay = 1000, interval = 300000) {
|
|
let retries = 0; // 当前重试次数
|
|
let isRunning = true; // 控制是否继续执行
|
|
|
|
// 内部重试逻辑
|
|
async function attemptRequest() {
|
|
try {
|
|
const res = await requestFn(); // 调用请求函数
|
|
|
|
// 检查请求是否成功
|
|
if (res.code == 200) {
|
|
// console.log("Request succeeded:", res);
|
|
// 如果请求成功,处理数据并设置定时器每隔指定时间重新发起请求
|
|
setTimeout(() => {
|
|
if (isRunning) {
|
|
attemptRequest();
|
|
}
|
|
}, interval);
|
|
} else {
|
|
throw new Error(`Request failed with code ${res.code}`);
|
|
}
|
|
} catch (error) {
|
|
console.error(`Attempt failed: ${error.message}`);
|
|
retries++;
|
|
|
|
if (retries <= maxRetries) {
|
|
console.log(`Retrying in ${retryDelay / 1000} seconds...`);
|
|
setTimeout(attemptRequest, retryDelay);
|
|
} else {
|
|
console.error(`Request failed after ${maxRetries} attempts: ${error.message}`);
|
|
isRunning = false; // 停止后续执行
|
|
}
|
|
}
|
|
}
|
|
|
|
// 启动第一次请求
|
|
attemptRequest();
|
|
|
|
// 提供一个停止函数
|
|
return {
|
|
stop: () => {
|
|
isRunning = false;
|
|
console.log("Request loop stopped.");
|
|
}
|
|
};
|
|
}
|
|
|
|
|
|
|