javascript - 在 Express.js 中请求超时后停止运行任务
问题描述
假设我们有下面的代码,它的超时设置为 5 秒。
router.get('/timeout', async (req, res, next) => {
req.setTimeout(5000, () => {
res.status(503)
res.send()
})
while (true) {
console.log("I'm alive")
}
res.status(200)
res.send({msg: 'success'})
})
我知道最后两行永远不会到达,但这不是重点。我要解决的问题是,尽管发送了响应,但 while 循环仍在工作。
有没有办法杀死这些仍在工作的任务?
解决方案
有两种类型的长时间运行的任务,两者的取消是不同的:
1)异步任务:
他们可能需要一段时间,但是他们没有使用 JavaScript 引擎,而是引擎处于空闲状态以等待一些外部数据(数据库/文件/计时器等)。在某些情况下(例如计时器),您可以轻松地丢弃该外部操作,也可以将其作为事件触发,因为引擎没有被阻塞并且可以处理取消。如果异步操作不能直接取消(例如数据库读取),您可以等到它完成后再取消它:
class Cancelable {
constructor() {
this.cancelled = false;
this.handlers = [];
}
onCancel(handler) { this.handlers.push(handler); }
cancel() {
this.cancelled = true;
this.handlers.forEach(handler => handler());
}
}
// inside of the request handler:
const canceller = new Cancelable;
req.setTimeout(5000, () => {
res.status(503);
res.send();
canceller.cancel(); // propagate cancellation
});
// Some long running, async cancellable task
const timer = setTimeout(function() {
res.send("done");
}, 10000 * Math.random())
// on cancellation just remove the timer
canceller.onCancel(() => clearTimeout(timer));
unCancellableAction(function callback() {
if(canceller.canceled) return; // exit early if it was cancelled
res.send("done");
});
2)同步任务:不能直接取消同步任务,因为引擎正忙于做任务,无法处理取消。要使它们可取消,您必须使用轮询,任务必须暂停其作业,检查是否应该取消,然后继续或中止。在 JS 中可以使用生成器函数完成(因为它们可以产生执行):
function runMax(time, action) {
const gen = action(), start = Date.now();
let done, value;
do {
({ done, value } = gen.next());
} while(!done && Date.now() < start + time)
return value;
}
// inside the request handler:
runMax(5000, function* () {
while(true) {
// ... some jobs
// yield at a safe position to allow abortion:
yield;
}
});
推荐阅读
- arrays - 什么时候数组 C-contiguous 和 F-contiguous 同时?
- jenkins - Scripted Pipeline 语法中并行内部的顺序阶段
- python - Python中多点下的面积积分
- r - 使用 mutate 将变量名称列表传递给自定义函数
- java - 为什么我的 Apache Ignite 持久存储仍处于锁定状态?
- python - 我无法在 pycharm 中导入 pygame
- elasticsearch - Logstash BeatsParser$InvalidFrameProtocolException
- java - 启动仪表 API 失败:Runner 意外退出
- javascript - 有没有办法使用“in”运算符排除某些元素?
- html - Bootstrap 4 - 如何实现这种布局