在Koa发送响应后运行代码

Gar*_*ett 3 javascript optimization generator ecmascript-6 koa

为了优化响应延迟,必须将响应发送回客户端之后执行工作.但是,在发送响应之后,我似乎能够获得运行代码的唯一方法是使用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'
Run Code Online (Sandbox Code Playgroud)

fel*_*ker 10

不要打电话ctx.res.end(),它是hacky并绕过koa的响应/中间件机制,这意味着你也可以只使用express.这是正确的解决方案,我也发布到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'
})
Run Code Online (Sandbox Code Playgroud)

不需要ctx.end()
,简而言之,做到

function *process(next) {
  yield next;
  processData(this.request.body);
}
Run Code Online (Sandbox Code Playgroud)

function *process(next) {
  yield next;
  yield processData(this.request.body);
}
Run Code Online (Sandbox Code Playgroud)