I would like to wrap an API request function in a loop to repeat the request in case of error OR give up if the error is persistent. I came up with this
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);
I was wondering if there is a more efficient way of doing this, perhaps with promises or callback functions?
Why not a recursive approach?
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)
I'm just simulating a rejection with a counter, but in your real world case, as long as your getDataAPI service rejects, it's going to retry until your catch block catches the rejection.