【问题标题】:Firestore take over a minute to get a document inside Firebase Cloud FunctionFirestore 需要一分钟多的时间才能在 Firebase Cloud Function 中获取文档
【发布时间】:2020-10-25 15:47:27
【问题描述】:

我正在尝试通过在 Firebase 的触发云功能中使用 firebase-admin 来获取文档:

exports.onTransactionCreated = functions.firestore
  .document("transaction/{id}")
  .onCreate((snapshot, context) => {
    const first = Date.now();
    admin.firestore().collection('myCollection').doc(snapshot.data().myDocumentId).get()
    .then((documentSnapshot) => {
      const second = Date.now();
      functions.logger.log(`seconds total = ${Math.floor((third - first) / 1000)}`);
    }
}

控制台日志显示这个结果:

seconds bw 1-2 elapsed = 140

使用的版本:

"engines": {
    "node": "12"
  },
 "dependencies": {
    "firebase-admin": "^9.2.0",
    "firebase-functions": "^3.11.0"
  }

在什么情况下可以检索到那么长的文档?即使在冷启动的情况下,我也不敢相信它会那么长。 这个问题实际上是我的应用程序的一个大痛点,任何帮助将不胜感激。

【问题讨论】:

    标签: javascript firebase performance google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您的函数需要返回一个在所有异步工作完成后解析的 Promise。现在,你的函数什么都不返回,这意味着它会在不等待任何东西的情况下终止。

    至少,您应该返回由get().then(...) 返回的承诺。

    exports.onTransactionCreated = functions.firestore
      .document("transaction/{id}")
      .onCreate((snapshot, context) => {
        const first = Date.now();
        return admin.firestore().collection('myCollection').doc(snapshot.data().myDocumentId).get()
        .then((documentSnapshot) => {
          const second = Date.now();
          functions.logger.log(`seconds total = ${Math.floor((third - first) / 1000)}`);
        }
    }
    

    请参阅documentation 了解更多信息。正确处理 Promise 是使函数正常工作的关键。

    【讨论】:

    • 非常感谢您的回答。我有一个回报 0;在我的 onCreate 结束时,我认为这就是所需要的。
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2018-05-13
    相关资源
    最近更新 更多