Koa.js прервать выполнение запроса

Как я могу завершить запрос в koa.js, используя другой запрос. Допустим, я сохраняю контексты активных запросов в объекте. Предположим, что запрос 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 ответ

Решение

Вы должны внедрить токен отмены, который вы регулярно проверяете.

Пример:

// 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 функция, чтобы вы могли контролировать отмену там.

Другие вопросы по тегам