首页 > 解决方案 > 云函数返回 NULL

问题描述

我正在构建一个应该从 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));

在此处输入图像描述

标签: javascripttypescriptgoogle-cloud-firestoregoogle-cloud-functions

解决方案


你没有正确处理承诺。没有理由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' }
        }
      });

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


推荐阅读