我有这个端点。此接口获取响应的时间较长。
app.get('/api/execute_script',(req,res) =>{
//code here
}我有以下终结点,它将终止进程
app.get('/api/kill-process',(req,res) => {
//code here
}但是除非第一个api得到响应,否则第二个api不会被执行。如何取消上一次api请求并执行第二次请求?
发布于 2020-05-11 17:35:52
您可以使用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 })
})https://stackoverflow.com/questions/61726124
复制相似问题