Koa.js中止运行请求

时间:2016-05-11 18:29:35

标签: 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'
      };
    }
  });

1 个答案:

答案 0 :(得分:2)

您应该实施定期检查的取消令牌。

示例:

// 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功能,以便您可以在那里控制取消。