0

Is there a recommended way to prevent a promises that doesn't ever settle from blocking an express route? I came up with this but wanted to know if there are preferable options.

app.use((req, res, next) => {
  const resultPromise = functionThatGetsAPromiseThatMightNotSettle();
  const timeoutPromise = new Promise((resolve, reject) => {
    setTimeout(() => reject('Timed Out', 10000);
  })

  Promise.race([resultPromise, timeoutPromise])
    .then(res.send)
    .catch(next)
})
ken_o
  • 374
  • 2
  • 8
  • [Using `Promise.race` for a timeout is just fine](https://stackoverflow.com/q/37120240/1048572), though preferably the function should then also have a way to cancel its task. And of course in general you should never really have a promise that never settles. – Bergi Feb 13 '18 at 21:56
  • Did you know that express already has a default request timeout built-in? See https://github.com/expressjs/express/issues/3330. – jfriend00 Feb 13 '18 at 23:36
  • Also `.then(res.send)` will not work as you have it. You lose the binding to `res`. You would need `.then(res.send.bind(res))` to fix that. – jfriend00 Feb 13 '18 at 23:38

0 Answers0