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

156
Visualizações
JavaScript skip await on pending fetch

I have an API fetch await code that fetches list of nodes in an array. The problem is, some of the nodes don't respond for whatever reason (being offline, wrong port, being programmed NOT to respond, ... ) and my code is stuck awaiting a reply from that node.

Is there any way to stop awaiting a fetch for example after 3 seconds if no response comes?

I tried using try and catch, but the nodes that don't respond don't return anything, the code is simply sitting there with no error or response.

Thank you!!

// list of nodes        
let nodes = [{
                "address": {
                    "hostname": "192.168.1.1",
                    "port": 31350
                }
            }, {
                "address": {
                    "hostname": "192.168.1.2",
                    "port": 31350
                }
            }
        ]
    
    
// api fetch function    
    async function fetchNodes(hostname, port) {
    
      const response = await fetch(`https://${hostname}:${port}/getstatus`, {
      method: 'post',
      body: JSON.stringify(body),
      headers: {'Content-Type': 'application/json'}
      });

      const data = response.json();   
      console.log(data);
    
    }
    
// loop to call api fetch function with all array entries       
    nodes.forEach(function(entry) {
     fetchNodes(entry.address.hostname, entry.address.port);
        }
    )
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

try this

 async function fetchWithTimeout(resource, options = {}) {
  const { timeout = 8000 } = options;
  
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
  const response = await fetch(resource, {
    ...options,
    signal: controller.signal  
  });
  clearTimeout(id);
  return response;
}

and use this function in you fetchNodes function

  async function fetchNodes() {
  try {
    const response = await fetchWithTimeout(
      `https://${hostname}:${port}/getstatus`,
      {
        timeout: 6000,
        method: "post",
        body: JSON.stringify(body),
        headers: { "Content-Type": "application/json" },
      }
    );
    const data = await response.json();
    return data;
  } catch (error) {
    // Timeouts if the request takes
    // longer than 6 seconds
    console.log(error.name === "AbortError");
  }
}
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