【发布时间】:2020-11-28 21:46:51
【问题描述】:
我们正在运行一个 Google Cloud Run 实例,并且我们正在特定端点上接收 Post 请求。当请求进入时,我们将其发布到 Pubsub 并触发一个 JavaScript 异步函数,其中包含 Prisma 数据库中的一些查询和突变。
我们目前没有等待这个,只是在这个函数调用准备好之前发送一个响应。
现在我想知道这对 Google Cloud Run 来说是否是好的行为。
一些示例代码:
app.post("/endpoint/example", async (req, res) => {
try {
const data = req.query.data
this.pubSubService.publish(data);
return res.send(200)
} catch (error) {
return res.send(400)
}
});
在 pubSubService 发布中,我们正在使用 db 突变/查询触发另一个异步函数。
我的问题是:
我们是否需要等待这个发布功能,是或否?为什么?
【问题讨论】:
-
您可能应该看看
awaitkeyword 的实际作用——它只是暂停async函数的执行“直到Promise被解决(即完成或拒绝),并且在完成后继续执行async函数。" -
Cloud Run 是一个 HTTP 请求/响应系统。当您的代码返回 HTTP 响应时,您的容器可能会被终止、CPU 空闲等。不要创建在 HTTP 响应之后继续执行的后台线程。
After startup, you should only expect to be able to do computation within the scope of a request: a container instance does not have any CPU allocated if it is not processing a request.cloud.google.com/run/docs/reference/container-contract -
所以@JohnHanley,如果我理解正确,我们确实需要等待,直到我们发送 res.send(200)。那么在每个查询/突变/承诺完成后,然后发送响应?
-
一旦您的代码返回 HTTP 响应,假设您的容器将被停止/终止。
标签: javascript node.js google-cloud-platform google-cloud-pubsub google-cloud-run