为了优化响应延迟,需要执行以下工作after响应已发送回客户端。但是,我似乎可以在发送响应后运行代码的唯一方法是使用setTimeout
。有没有更好的办法?也许在发送响应后在某个地方插入代码,或者在某个地方异步运行代码?
这是一些代码。
koa = require 'koa'
router = require 'koa-router'
app = koa()
# routing
app.use router app
app
.get '/mypath', (next) ->
# ...
console.log 'Sending response'
yield next
# send response???
console.log 'Do some more work that the response shouldn\'t wait for'
不要打电话ctx.res.end()
,它是 hacky 的并且规避了 koa 的响应/中间件机制,这意味着你也可以只使用express。
这是正确的解决方案,我也发布到https://github.com/koajs/koa/issues/474#issuecomment-153394277 https://github.com/koajs/koa/issues/474#issuecomment-153394277
app.use(function *(next) {
// execute next middleware
yield next
// note that this promise is NOT yielded so it doesn't delay the response
// this means this middleware will return before the async operation is finished
// because of that, you also will not get a 500 if an error occurs, so better log it manually.
db.queryAsync('INSERT INTO bodies (?)', ['body']).catch(console.log)
})
app.use(function *() {
this.body = 'Hello World'
})
不需要ctx.end()
简而言之,做
function *process(next) {
yield next;
processData(this.request.body);
}
NOT
function *process(next) {
yield next;
yield processData(this.request.body);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)