首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Koa.js中止运行请求

Koa.js中止运行请求
EN

Stack Overflow用户
提问于 2016-05-11 18:29:34
回答 1查看 1.3K关注 0票数 2

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

代码语言:javascript
复制
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'
      };
    }
  });
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-12 07:13:53

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

示例:

代码语言:javascript
复制
// 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函数,以便在那里控制取消。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37170668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档