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

编程入门 行业动态 更新时间:2024-10-09 18:18:11

如何取消<a href=https://www.elefans.com/category/jswz/34/1642341.html style=先前的快递请求,以便执行新请求?"/>

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

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

更多推荐

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

本文发布于:2024-05-07 11:10:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755967.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:先前   快递

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!