如何在Firebase Cloud的Express服务器中的res.send()之后执行代码 [英] How to exec code after res.send() in express server at Firebase cloudFunctions
问题描述
我正在使用云功能构建快速服务器,但是我遇到了 res.send()
的问题.在普通快递服务器中,我在 res.send()
之后执行一些代码,但是在我的快递服务器中,使用Firebase cloudFunctions res.send()
可以关闭我的连接,之后什么也不要执行.
I'm building an express server using the cloud functions, but I facing a problem with res.send()
.
In a common express server I can exec some code after res.send()
but at my express server using the Firebase cloudFunctions res.send()
closes my connection and I can't exec anything after that.
这是我需要做的:在我的服务器中,我有一个端点从Slack api对话框接收一些数据,然后Slack Api等待空响应 res.send()
,所以我需要发送它.但是我还需要将这些数据保存在数据库中,然后以松弛状态发送一条消息给我的用户您的帖子已保存!" 所以我的端点会做什么:
Here is what I need to do:
In my server I have an endpoint to receive some data from Slack api dialog, and after that Slack Api is waiting for a empty response res.send()
, so I need to send it.
But I also need to save that data in my DB, and send a message in slack to my user "Your post was saved!"
So what my endpoint does:
async function myEndpoint(req, res) {
await savePayload(req.payload);
await sendUserMessage(req.payload);
res.send('');
}
但是有时候 res.send()
需要很长时间才能开始运行,并且在松弛时出现错误,所以我想做些类似的事情:
But sometimes res.send()
takes to long to start running and I get an error on slack, so I would like to do something like:
async function myEndpoint(req, res) {
res.send('');
await savePayload(req.payload);
await sendUserMessage(req.payload);
}
但是正如我所说,在 res.send('')
之后,我的连接已关闭,并且下一行没有运行.您知道我该如何解决吗?
But as I said, after res.send('')
my connection is closed and the next lines doesn't run. Do you know how can I work around that ?
推荐答案
响应完成后,HTTP函数立即终止执行-这是Cloud Functions的基本架构,因此无法解决.您将需要:
HTTP functions immediately terminate execution once the response is completed -- this is fundamental architecture for Cloud Functions, so there is no way around it. You will need to either:
- 优化代码路径,以使空响应始终在截止日期之前发送,或者
- 触发将异步执行工作的后台函数执行,然后进行响应.这可以通过例如写入Cloud Firestore或发送发布/订阅消息
这篇关于如何在Firebase Cloud的Express服务器中的res.send()之后执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!