【发布时间】:2020-01-01 00:15:42
【问题描述】:
当请求超时时如何停止 Express 中的进程?
安装“连接超时”import timeout from 'connect-timeout';
// halt_on_timeout.js
module.exports = function haltOnTimedout(req, res, next) {
if (!req.timedout) next();
};
昂贵的过程需要超过 30 秒
路线超时,但expensive_long_operation 永远不会停止运行..
route.post(
'upload_alot_of_content/'
timeout('30s'),
haltOnTimedout,
async (req, res) => {
const result = await expensive_long_operation();
if (req.timedout) {
next('error!')
}
res({....})
})
【问题讨论】:
-
expensive_long_operation()到底是什么。除非您将它放在另一个进程中,否则您将如何处理尝试取消某些异步进程完全取决于它是什么以及它正在等待什么,这需要很长时间。如果它不是异步的,那么它只会占用 CPU 并且不会运行其他任何东西,因此您必须在内部停止它以运行长时间运行的代码。
标签: node.js express error-handling timeout