Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!