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

239
Visualizações
How in a try/catch return something or null depending if it fails after a finite number of retries

In a NodeJs backend, I need to implement a function which tries for 10 times max to retrieve the data from a request.

The retry need to be waiting for 15s before hit again the request.

If on the first try the request succeed I have to return the data.

If it fails it is retiring 10 times and after that on the 10th time fails, has to return null.

My issue is with following function:

// Helper for the waiting
const sleep = (ms) => {
 return new Promise((resolve) => {
   setTimeout(resolve, ms);
  });
};

async function getData(documentId, log) {
  const MAX_RETRIES = 10;
  const timeout = 15000;

  for (let i = 0; i <= MAX_RETRIES; i += 1) {
    try {
      const { icfDocuments } = await request(
        CONSENT_SERVICE_URL,
        getICFDocumentRecipientsQuery,
        {
          documentId,
        }
      );
      // if the pdfUrl is present return the data
      if (icfDocuments.nodes[0].revision.pdfUrl) return icfDocuments;
    } catch (err) {
      log.debug('Waiting for retrieve the last revision pdfUrl', timeout, 'ms');
      await sleep(timeout);
      log.debug('Retrying', err.message, i);
    }
  }
  // What here ??? return data or null ???
  return null;
}

What I need to wait is that pdfUrl to be present in the data. Not to be null. If it is null than should be retry max 10 times to see if we get that pdfUrl. If that fails I return null. If that success I return the data.

At the moment this above not really work and not sure how to make it correct to get the right output.

about 4 years ago · Juan Pablo Isaza
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