javascript - Koa.js 中止正在运行的请求

标签 javascript node.js koa

如何使用另一个请求结束 koa.js 中的请求。假设我将事件请求上下文保存在一个对象中。假设请求A已启动并且需要很长时间。我怎样才能发出另一个请求,告诉请求 A 结束。

var requests = {};

// middleware to track requests
app.use(function*(next) {
    var reqId = crypto.randomBytes(32).toString('hex');
    requests[reqId] = {
      context: this
    }

    yield next;

    delete requests[reqId];
  }
);

  // route to kill request using ID generated from middleware above
  router.get('/kill/:reqId', function *(next) {
    var req = requests[this.params.reqId];

    if (req) {
      // abort request here
    } else {
      this.body = {
        error: 'Request not found'
      };
    }
  });

最佳答案

您应该实现定期检查的取消 token 。

示例:

// Factory to create a token
const cancellationToken = () => {
  let _cancelled = false;

  function check() {
    if (_cancelled == true) {
      throw new Error('Request cancelled');
    }
  }

  function cancel() {
    _cancelled = true;
  }

  return {
    check: check,
    cancel: cancel
  };
}


const reqs = {};

// Middleware to create tokens.
app.use(function *(next) {
  const reqId = crypto.randomBytes(32).toString('hex');
  const ct = cancellationToken();
  reqs[reqId] = ct;
  this.cancellationToken = ct;
  yield next;

  delete reqs[reqId];
});

// route to kill request using ID generated from middleware above
router.get('/kill/:reqId', function *(next) {
  const ct = requests[this.params.reqId];

  if (ct) {
    ct.cancel();
  } else {
    this.body = {
      error: 'Request not found'
    };
  }
});

// A request checking for cancellation.
router.get('/longrunningtask', function *(next) {
  for (let i = 0; i < 1000; i++) {
    yield someLongRunningTask(i);
    // This is where you check to see if you're done.
    // The method will throw and abort the request.
    this.cancellationToken.check();
  }
});

您甚至可以将取消 token 传递给 someLongRunningTask 函数,以便您可以在那里控制取消。

关于javascript - Koa.js 中止正在运行的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170668/

相关文章:

javascript - 从数组中过滤非 -"linear"的渐进值

javascript - HTML/PHP/JQUERY - 选择正确的国家/地区时,将表单中的文本输入类型字段更改为选择器字段,否则将字段保留为文本框输入

node.js - 使用 asyncjs 保存多个 Mongoose 对象不起作用

javascript - 如何以编程方式打开我从 Electron DesktopCapurer.getSources 获得的窗口

node.js - 子路由无法在 koa-router 的单独文件中工作

javascript - 为什么我总是得到 NaN?

javascript - 如何将 Canvas 数据保存到文件

node.js - 在nodejs中使用全局变量有多糟糕?

javascript - 如何跳过或跳转中间件? ( Node )

javascript - 如何在 Koa 中指定静态文件夹?