简体   繁体   English

Next.js:发送 HTTP 响应后如何执行代码?

[英]Next.js: How to execute code after sending HTTP response?

In Express you can execute code after sending an HTTP response like this:在 Express 中,您可以在发送 HTTP 响应后执行代码,如下所示:

res.send()
await someAsyncFunction() // imagine this takes a very long time

In Next.js, at least when testing code in a local environment, the above works the same as express.在 Next.js 中,至少在本地环境中测试代码时,上面的工作方式与 express 相同。 However, once deployed on Vercel, the above code seems to stop execution after sending the HTTP response.但是,一旦部署在 Vercel 上,上面的代码似乎在发送 HTTP 响应后停止执行。 I don't know if this is just because that's how their serverless functions are set up or what.我不知道这是否只是因为他们的无服务器功能是这样设置的还是什么。 So I'm forced to rearrange it like this:所以我不得不像这样重新排列它:

await someAsyncFunction() // imagine this takes a very long time
res.send()

The problem with ordering it like that is if the async function is very slow, the response could time out before it gets sent back.像这样排序的问题是,如果异步函数非常慢,响应可能会在它被发回之前超时。 There are situations where that is bad.在某些情况下,这很糟糕。 Say I need to send a bunch of emails using a rate-limited API.假设我需要使用限速 API 发送一堆电子邮件。 That can take a long time.这可能需要很长时间。 I need to send a HTTP response right away before moving on to the very slow process of sending all the emails.在继续发送所有电子邮件的非常缓慢的过程之前,我需要立即发送 HTTP 响应。

I haven't been able to find explicit documentation explaining this behavior, but this GitHub discussion appears to confirm that you cannot execute code after sending an HTTP response if you are deploying on Vercel: https://github.com/vercel/next.js/discussions/14077我无法找到解释此行为的明确文档,但此 GitHub 讨论似乎确认如果您在 Vercel 上部署,则在发送 HTTP 响应后无法执行代码: https://github.com/vercel/next。 js/讨论/14077

Thus I am stuck sending the response last.因此,我被困在最后发送响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM