Koa.js中止运行请求

Koa.js abort running request

本文关键字:运行 请求 js Koa      更新时间:2023-09-26

如何使用另一个请求在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'
      };
    }
  });

您应该实现一个定期检查的取消令牌。

示例:

// 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();
  }
});

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