【问题标题】:Firebase functions sporadically don't complete executionFirebase 函数偶尔无法完成执行
【发布时间】:2018-07-27 17:12:28
【问题描述】:

我已经构建了一个由 Firestore“文档创建”事件触发的 Firebase 云功能

该函数连接到 MongoDB 集群(在 MongoDB Atlas 上运行),修改 Firestore 数据将其存储在数据库的集合中

函数本身在每次写入文档时都会执行

但它没有完成执行,这是零星的,例如大约 10 次中的 1 次,执行将不会完成,即“错误连接”或“连接成功”行均未执行

同样的代码被执行了 9/10 次(大约)

这是代码的精简版

import * as functions from 'firebase-functions';
import { MongoClient } from "mongodb";

exports.migrate = functions.firestore
    .document('{rootCollection}/{tenantName}/users/{userId}/entry/{entryId}')
    .onCreate((snap, context) => {

    const uri = "mongodb://localhost:27017/";

    console.log("Attempting to connect to mongoclient");

    MongoClient.connect(uri, function(err, client) {

        if (err) {
                console.log("error connecting");
                return 1;
            }        
            else if (client) {
              console.log("Connected to mongoclient");
              //write to mongodb collection here
            }
       });
});

这是一次成功的执行,红色的日志消息突出显示了在 MongoClient 连接后执行的块内的代码(打印了一些额外的日志消息)

这是一个不成功的执行

编辑:

Doug 的回答提示,这就是我解决它的方法 - 我们不仅需要返回一个承诺,还需要链接连接返回的承诺和插入语句

exports.migrate = functions.firestore
.document('{rootCollection}/{tenantName}/users/{userId}/entry/{entryId}')
    .onCreate((snap, context) => {

    const uri = "mongodb://localhost:27017/";

    console.log("Attempting to connect to mongoclient");

    return MongoClient.connect(uri).then((client) => {
        console.log("Connected successfully");
        return client.db("test")
            .collection("testcollection")
            .insertOne({"name": "1"})
                .then((() => {
                    console.log("inserted successfully");
                    client.close(true)
                        .then(()=>{console.log("connection close OK")})
                        .catch(()=>{console.log("connection close Err")});
                }))
                .catch(() => {
                    console.log("error in insertion");
                    client.close(true)
                        .then(()=>{console.log("connection close OK")})
                        .catch(()=>{console.log("connection close Err")});
                });

    })
    .catch(() => console.log("connection failure"));

而且我确定这一次,因为我可以在云功能日志中看到它们,所以代码按照我想要的顺序执行:

  1. 功能已启动(系统消息)
  2. 正在尝试连接(用户消息)
  3. 连接成功(用户消息)
  4. 插入成功(用户消息)
  5. 连接已关闭(用户消息)
  6. 功能结束(系统消息)

【问题讨论】:

    标签: mongodb firebase google-cloud-functions


    【解决方案1】:

    您需要返回一个仅在函数中的所有工作完成后才解析的 Promise。 MongoClient.connect() 几乎可以肯定是一个立即返回的异步函数,并且您传递给它的回调会在一段时间后执行。因为它会立即返回,所以您的数据库触发器会立即返回,并且 Cloud Functions 会假定其工作已完成。在 Cloud Functions 关闭您的函数之前,您的回调似乎只是偶尔被调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-17
      • 2021-06-06
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 2017-08-16
      相关资源
      最近更新 更多