我有这个终点。该API需要很长时间才能获得响应。
app.get('/api/execute_script',(req,res) =>{
//code here
}
我有以下端点将终止进程
app.get('/api/kill-process',(req,res) => {
//code here
}
,但除非第一个api得到响应,否则第二个api不会执行。如何取消上一个api请求并执行第二个请求?
答案 0 :(得分:2)
您可以使用EventEmitter
杀死另一个进程,您只需要一个会话/用户/进程标识符即可。
const EventEmitter = require('events');
const emitter = new EventEmitter();
app.get('/api/execute_script', async(req,res,next) => {
const eventName = `kill-${req.user.id}`; // User/session identifier
const proc = someProcess();
const listener = () => {
// or whatever you have to kill/destroy/abort the process
proc.abort()
}
try {
emitter.once(eventName, listener);
await proc
// only respond if the process was not aborted
res.send('process done')
} catch(e) {
// Process should reject if aborted
if(e.code !== 'aborted') {
// Or whatever status code
return res.status(504).send('Timeout');
}
// process error
next(e);
} finally {
// cleanup
emitter.removeListener(eventName, listener)
}
})
app.get('/api/kill-process',(req,res) => {
//code here
const eventName = `kill-${req.user.id}`;
// .emit returns true if the emitter has listener attached
const killed = emitter.emit(eventName);
res.send({ killed })
})