【问题标题】:How could I handle timeout request in koa?如何在 koa 中处理超时请求?
【发布时间】:2015-07-02 06:18:40
【问题描述】:

例如:

var app = require('koa')();
app.use(function *(next) {
    var start = new Date();
    yield next;
});
app.use(function *(next) {
    var result = yield loadData();
    this.body = result;
});
app.listen(8080);

假设如果loadData返回数据超过1秒,那么我想要this.body = 'there is a timeout'。我怎么能做到这一点?我不认为setTimeout 能够处理这个问题。我尝试了this.response.setTimeout 函数,但它说setTimeout 是未定义的。感谢您的任何建议

【问题讨论】:

  • 刚刚查找了npm注册表并找到了这个包:koa-timeout。看起来像你想要的。
  • 感谢您的建议,但我认为这不能解决我的问题。也许我没有详细描述我的问题。无论如何将loadData 转换为异步函数?当异步函数返回结果时,我想将结果提供给this.body。似乎没有办法......有什么建议吗?我必须为loadData 函数编写c++ 代码吗?

标签: node.js koa


【解决方案1】:

您可以随时将其转换为 Promise。喜欢

`loadData().then((onCompletion) => {
//take the time here
timeOut = timeEnd - timeStart;
timeOut >= 1sec ? this.body = 'there is a timeout' : this.body = onCompletion 
}).((onFailure) => {
//do something if it fails
});`

当然,除非您的 loadData 返回一个承诺,否则这将不起作用

【讨论】:

  • 是的,如果不修改loadDatakoa 的底层代码,我认为我无法实现我的目标。谢谢你的回复:)
【解决方案2】:

我想这就是你要找的。您使用 loadData() 产生断言超时,并将第二个参数作为 int 传递(以毫秒为单位),在您的情况下为 1000

https://github.com/cojs/assert-timeout

【讨论】:

    【解决方案3】:

    试试看

    var app = require('koa')();
    app.use(function *(next) {
        this.req.connection.setTimeout(0);
        var start = new Date();
        yield next;
    });
    app.use(function *(next) {
        var result = yield loadData();
        this.body = result;
    });
    app.listen(8080);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      相关资源
      最近更新 更多