Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda