请求完成后如何继续运行Firebase Cloud Function [英] How to continue running Firebase Cloud Function after request is finished

查看:46
本文介绍了请求完成后如何继续运行Firebase Cloud Function的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很奇怪,Firebase似乎不像典型的Express应用程序那样工作.无论我在Express中写什么,然后将其复制粘贴到Firebase Functions中,通常都会出错.我有一个我自己无法解决的问题.

Really bizarre that Firebase doesn't seem to work quite like typical Express app. Whatever I write in Express and copy-paste to Firebase Functions I typically get error. There is one that I can't figure out on my own though.

此端点旨在启动功能,并且寿命足以完成更长的任务.该请求是一个Webhook(发送文档,我们将对其进行转换并在完成操作后ping您指定另一个Webhook).下面是非常简化的示例:

This endpoint is designed to start a function and live long enough to finish even longer task. That request is a webhook (send docs, we will transform them and ping you when it's done to specified another webhook). Very simplified example below:

router.post('/', (req, res) => {
  try {
    generateZipWithDocuments(data) // on purpose it's not async so request can return freely
    res.sendStatus(201)
  
  } catch (error) {
    res.send({ error })
  }
})

在我的本地计算机上,它可以工作(纯Express应用程序和本地模拟的Firebase函数),但是在云中却有问题,即使我放了一段 console.log(),我也没有没有太多的信息.Firebase没有错误.

On my local machine it works (both pure Express app and locally emulated Firebase Functions), but in the cloud it has problems and even though I put a cavalcade of console.log() I don't get much information. No error from Firebase.

推荐答案

如果 generateZipWithDocuments()不是异步的 res.sendStatus(),将在其后立即执行,并且 Cloud Function将终止(并且 generateZipWithDocuments()完成的工作将不会完成).有关更多详细信息,请参见文档此处.

If generateZipWithDocuments() is not asynchronous res.sendStatus() will be immediately executed after it, and the Cloud Function will be terminated (and the job done by generateZipWithDocuments() will not be completed). See the doc here for more details.

您有两种可能性:

  1. 您将其设为异步,然后等待其工作完成后再发送响应.通常,您通常使用 async/await .请注意,Cloud Function的最大执行时间为9分钟.
  2. 您将长时间执行的工作委派给另一个Cloud Function,然后然后,发送响应.要将任务委派给另一个Cloud Function,您应该使用Pub/Sub.请参见发布/订阅触发器此SO线程,以获取有关如何实现该操作的更多详细信息.在发布/订阅触发功能中,完成工作后,您可以通过电子邮件通知用户
  1. You make it asynchronous and you wait its job is completed before sending the response. You would typically use async/await for that. Note that the maximum execution time for a Cloud Function is 9 minutes.
  2. You delegate the long time execution job to another Cloud Function and, then, you send the response. For delegating the job to another Cloud Function, you should use Pub/Sub. See Pub/Sub triggers, the sample quickstart, and this SO thread for more details on how to implement that. In the Pub/Sub triggered Function, when the job is done you can inform the user via an email, a notification, the update of a Firestore document on which you have set a listener, etc... If generateZipWithDocuments() takes a long time, it is clearly the most user friendly option.

这篇关于请求完成后如何继续运行Firebase Cloud Function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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