发送响应后继续执行(Cloud Functions for Firebase) [英] Continue execution after sending response (Cloud Functions for Firebase)

查看:23
本文介绍了发送响应后继续执行(Cloud Functions for Firebase)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Firebase 函数与 https 触发器一起使用,我想知道在向客户端发送响应后多久,函数会继续执行.我想向客户端发送响应,然后执行另一个操作(发送邮件).目前我这样做如下:

I'm using Firebase Functions with https triggers, and I was wondering how long after sending the response to the client, the functions keeps executing. I want to send a response to the client and then perform another operation (send a mail). Currently I'm doing this as following:

module.exports.doSomeJob = functions.https.onRequest((req, res) => {
    doSomeAsyncJob()
    .then(() => {
        res.send("Ok");
    })
    .then(() => {
        emailSender.sendEmail();
    })
    .catch(...);
});

上面的代码对我有用,但我怀疑该代码只能工作,因为在 res.send 完成之前发送邮件已经完成,所以我想知道终止过程是如何工作以确保代码不会中断.

The above code is working for me, but I'm suspecting that the code only works because sending the mail has finished before the res.send has completed, so I was wondering how exactly the termination process is working to make sure the code will not break.

推荐答案

您应该期望 HTTP 函数在您发送响应后立即终止.任何其他行为都是运气或竞争条件的某种组合.不要写靠运气的代码.

You should expect that the HTTP function terminates the moment after you send the response. Any other behavior is some combination of luck or a race condition. Don't write code that depends on luck.

如果您需要在工作完全完成之前向客户端发送响应,您将需要启动第二个函数以从 HTTP 函数停止的地方继续.使用 pub/sub 函数来处理是很常见的.让 HTTP 函数向另一个函数发送 pub/sub 消息,然后仅在消息发送后终止 HTTP 函数(通过发送响应).

If you need to send a response to the client before the work is fully complete, you will need to kick off a second function to continue where the HTTP function left off. It's common to use a pub/sub function to do with. Have the HTTP function send a pub/sub message to another function, then terminate the HTTP function (by sending a response) only after the message is sent.

这篇关于发送响应后继续执行(Cloud Functions for Firebase)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆