我想在循环中包装一个API请求函数,以便在出现错误时重复请求,或者如果错误持续存在则放弃请求。我想到了这个
let data;
let all_ok = false;
let counter = 0;
do {
data = await getDataAPI(token_id);
counter++;
if (! await checkAPIerrors(data)) { // something bad happened
await sleep(5000);
} else {
all_ok = true;
}
if (counter > 10) {
throw "getDataAPI error"; // stop execution, there is a serious problem
}
} while (!all_ok);
我想知道是否有一种更有效的方法来做到这一点,也许是承诺或回调函数?
为什么不使用递归方法呢?
let counter = 0
const getDataAPI = () => new Promise((res, rej) => setTimeout(counter < 5 ? rej : res, 2000))
const sleep = (t) => new Promise(r => setTimeout(r, t))
const fetchRecursively = async(id) => {
counter++
try {
const data = await getDataAPI(id);
console.log("Success!", id)
} catch (e) {
console.log("FAILED, retrying in 5 seconds... ", 5 - counter, " attempts left.")
await sleep(5000)
fetchRecursively(id)
}
}
fetchRecursively(123)
我只是用计数器模拟拒绝,但在您的现实世界中,只要您的getDataAPI
服务拒绝,它就会重试,直到您的catch块捕获拒绝。