首页 > 解决方案 > Firestore 需要一分钟多的时间才能在 Firebase Cloud Function 中获取文档

问题描述

我正在尝试通过在 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"
  }

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

标签: javascriptfirebaseperformancegoogle-cloud-firestoregoogle-cloud-functions

解决方案


您的函数需要返回一个在所有异步工作完成后解析的承诺。现在,您的函数什么也不返回,这意味着它将终止而无需等待任何东西。

最低限度,您应该返回由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)}`);
    }
}

请参阅文档以获取更多信息。正确处理 Promise 是使函数正常工作的关键。


推荐阅读