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

317
Visualizações
fetch API - execute the same code after a connection timeout as if the response status code was not 200

I am trying to understand the fetch API a little better:

When making a GET-request such as below, I could simply check the status-code of the response and only then do something if the status-code equals 200.

let response = fetch(url, {method: 'GET'});
if (response.status === 200) {
    // do something
} else {
    console.log("GET request was not successfull");
}

I have read that it might be a good idea to set a connection timeout for the fetch-request. I could use an AbortController for this purpose:

function fetchWithTimeout(url, method) {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 8000);
    response = await fetch(url, {method, signal: controller.signal});
    clearTimeout(timeoutId);
    return response;
}

If the connection actually times out, an AbortError is thrown. In this case, I would like to log the exact same error message as if the connection did not time out, but the response status-code was not equal to 200. And I cannot think of any better solution for this than the following:

try {
    let response = fetchWithTimeout(url, 'GET');
    if (response.status === 200) {
        // do something
    } else {
        console.log("GET request was not successfull");
    }
} catch (AbortError e) {
    console.log("GET request was not successfull");
}

I don't like this code, since it is redundant. In this case it is not too bad, as I am only logging a message. But potentially, I could do more and I just want to execute the same code for both scenarios. Does somebody have an idea as on how to achieve this?

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