Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda