【问题标题】:Cloud Function Returns NULL云函数返回 NULL
【发布时间】:2020-04-14 22:01:24
【问题描述】:

我正在构建一个云函数,它应该从 Firestore 返回文档快照。在云函数日志中,它控制台记录文档中的数据,但是当我从 React-Native 调用它时,它返回 null。

这是函数本身的代码。

export const getUserProfile = functions.https.onCall((data, context) => {

  return new Promise((resolve, reject) => {
    const info = admin
      .firestore()
      .collection("users")
      .doc("za5rnpK69TQnrvtNEsGDk7b5GGJ3")
      .get()
      .then((documentSnapshot) => {
        console.log("User exists: ", documentSnapshot.exists);

        if (documentSnapshot.exists) {
          console.log("User data: ", documentSnapshot.data());

          documentSnapshot.data();
        }
      });
    resolve(info);
  });
});

还添加了来自 React-Native 的代码来调用该函数。

functions()
    .httpsCallable("getUserProfile")({})
    .then(r => console.log(r));

enter image description here

【问题讨论】:

    标签: javascript typescript google-cloud-firestore google-cloud-functions


    【解决方案1】:

    您没有正确处理承诺。这里根本没有理由使用new Promise。 (事实上​​,它很少需要——只有当你调用的 API 不使用 Promise 而只使用回调函数时。)如果你试图将文档的内容返回给调用者,这就是你所需要的。 :

        return admin
          .firestore()
          .collection("users")
          .doc("za5rnpK69TQnrvtNEsGDk7b5GGJ3")
          .get()
          .then((documentSnapshot) => {
            if (documentSnapshot.exists) {
              return documentSnapshot.data();
            }
            else {
              return { whatever: 'you want' }
            }
          });
    

    如果没有文件,您必须决定希望客户收到什么。

    【讨论】:

    • 太棒了!这对我有用!除此之外,有没有办法将它作为参数传递,而不是对 documentID 进行硬编码?如果我尝试 "firestore().collection("users").doc(docID).get()" 我会收到一个未处理的错误,如下所示: Unhandled error Error: Value for argument "documentPath" is not a valid resource path .路径必须是非空字符串。
    • 是的,这在可调用函数的文档中有所介绍。如果您对此有任何疑问,请单独发布,因为 Stack Overflow 上的每个帖子只允许一个问题。
    • 好人!感谢所有的帮助。检查了文档并发现了我的错误。
    猜你喜欢
    • 2014-05-12
    • 1970-01-01
    • 2021-03-04
    • 2019-02-27
    • 2021-01-24
    • 2019-08-20
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多