我怎么能在koa处理超时请求?

时间:2015-07-02 06:18:40

标签: node.js koa

例如:

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未定义。感谢您的任何建议

3 个答案:

答案 0 :(得分:0)

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

`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返回一个promise

,否则这将不起作用

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

试试吧

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);