Koa.js中止运行请求
Koa.js abort running request
如何使用另一个请求在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
函数,以便在那里控制取消。
相关文章:
- Javascript-如何让脚本与Ajax请求的数据一起运行
- Koa.js中止运行请求
- 在Flask中使用.getJSON请求时,只运行一次命令
- 如何在node+express中重新运行请求处理程序
- 在安装后首次运行应用程序时从 UIBebView 发出 jQuery Ajax 请求
- 防止请求动画帧一直运行
- [XSS]Expressjs 阻止从 POST 请求运行脚本
- 当ajax请求发生时运行代码的Chrome扩展
- 中止以前运行的Ajax请求
- 在document.ready jquery上运行ajax请求
- 无法连接到网络服务器.验证 Web 服务器是否正在运行,并且传入的 http 请求未被防火墙阻止
- 循环遍历 Angular HTTP 请求中的对象,等到响应后再运行下一个循环
- 将 CORS 请求发布到运行 sailsjs 的 HTTPS 域
- 我可以/如何显式终止长时间运行的 xhr 请求
- 如何注册要在更新面板请求完成时运行的函数
- 在运行应用并切换到路由或状态之前解决$http请求
- AJAX 可访问的长时间运行的服务任务阻止在启用 ASP.NET 兼容性/会话的环境中的后续 AJAX 服务请求
- 阻止其他代码运行,直到 AJAX 请求返回某些内容
- Ajax Post请求总是运行错误功能,尽管卷曲到相同的url工作正常
- 运行请求,直到响应是用$q请求的