如何取消以前的快速请求,以便执行新请求?



我有这个端点。此 API 需要很长时间才能获得响应。

app.get('/api/execute_script',(req,res) =>{
//code here
}

我有以下端点,它将终止进程

app.get('/api/kill-process',(req,res) => {
//code here
}

但除非第一个 API 得到响应,否则第二个 API 不会被执行。如何取消上一个 api 请求并执行第二个请求?

您可以使用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 })
})

最新更新