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

118
Visualizações
Stop express router callback function execution on timeout

I need to define a timeout for specific routes in Express so that instead of getting a server default timeout error, my API returns JSON data. I add it like this to the beginning of the router.get callback function

    router.get('/', function (req, res, next) {
      res.setTimeout(10000, function () {
         res.status(500).json({ error: 'Response Processing Timed Out.' });
      });
      /*
       some time-consuming code here
      */
     res.json(result); //this should never happen if timeout occurs 
    });

and that (timeout part) works OK (it returns JSON error message to the client on timeout, as expected).

The problem is that the rest of the code is still executed and when it gets to the regular res.json method - res.json(result) I get the error ERR_HTTP_HEADERS_SENT (as it should be, because it tries to do another res.json after the one containing the error message has already been sent)

If that was an ordinary check for errors I would add a return statement after res.json, but it is not - it is inside a callback function and a return would just end the callback, but not the parent function (in this case router.get callback function). I know that I could set some variable to true when timeout occurs and then check if it is true before any res.json, but I'd like to avoid that (I have quite a few res.json lines in the function, and also I'd like to avoid executing time-consuming code if the error message has already been sent)

Any ideas on how to solve this? If res.setTimeout is not the proper way, I'll be glad to learn the right way to do this.

Thanks

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