Koa.js中止运行请求

如何使用另一个请求在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函数,以便您可以控制取消。