'Loop function until response is OK or error is persistent

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cesare Polonara