最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin19浏览0评论

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

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

我有这个端点。此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 })
}
发布评论

评论列表(0)

  1. 暂无评论