gpt4 book ai didi

javascript - 在 Koa 发送响应后运行代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:33:23 25 4
gpt4 key购买 nike

要优化响应延迟,有必要将响应发送回客户端后执行工作。但是,我似乎可以让代码在发送响应后运行的唯一方法是使用 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

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

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

关于javascript - 在 Koa 发送响应后运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26516082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com