本文介绍了响应已由Koa发送后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要优化响应延迟,必须在将响应发送回客户端后进行 的工作.但是,我似乎可以使代码在发送响应后运行的唯一方法是使用setTimeout.有没有更好的办法?也许是在响应发送后插入代码的地方,还是异步运行代码的地方?

To optimize the response delay, it is necessary to perform work after are response has been sent back to the client. However, the only way I can seem to get code to run after the response is sent is by using setTimeout. Is there a better way? Perhaps somewhere to plug in code after the response is sent, or somewhere to run code asynchronously?

这是一些代码.

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

Do NOT call ctx.res.end(), it is hacky and circumvents koa's response/middleware mechanism, which means you might aswell just use express.Here is the proper solution, which I also posted to 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()
简而言之,

No need for ctx.end()
So in short, do

function *process(next) {
  yield next;
  processData(this.request.body);
}

function *process(next) {
  yield next;
  yield processData(this.request.body);
}

这篇关于响应已由Koa发送后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 12:51