Firestore .get()承诺停留在待处理状态

时间:2020-05-22 03:24:18

标签: javascript reactjs firebase google-cloud-firestore

我正在使用React和Firebase创建一个小型应用程序。我正在尝试在我的Firestore数据库中检查与用户相关的文档,该文档的ID与firebase auth生成的uid相同,但是由于某些原因.get()承诺仍处于待处理状态,导致.exists( )函数引发错误(TypeError:userDoc.exists不是函数)。我最初以为这是我的数据库规则的问题,所以我更改了它们,以便任何人都可以读写数据库(我知道这是不安全的,以后会更改规则)。

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

即使在此之后,我仍然无法检索该文档。下面是我的代码。

let userDoc = db.collection('Users').doc(currentUser.uid)
console.log(userDoc);
userDoc = userDoc.get();
console.log(userDoc);
userDoc = userDoc.exists();

db是使用以下内容创建的Firestore对象

admin.initializeApp()
db = admin.firestore()

let userDoc = db.collection('Users').doc(currentUser.uid)产生一个DocumentReference对象。该文档存在于Firestore中,但由于某种原因我无法在我的react应用程序中访问它。我编写了一个也可以与firestore一起使用的云函数,并且对我的数据库进行读写没有问题。我觉得我在这里缺少任何东西,非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

userDoc.get();promise,它通过.get()发出请求,因此它将处于待处理状态。

然后将exists()更改为exists REF

userDoc.get().then(data => {
   console.log(data , data.exists); //<--- Try to check here
});

console.log(userDoc); // <--- this will give you Promise with pending state

或者您可以使用async await

async function getData() { // <------ async
    let userDoc = db.collection('Users').doc(currentUser.uid)
    console.log(userDoc);
    userDoc = await userDoc.get(); // <------ await
    console.log(userDoc);
    userDoc = userDoc.exists; // <------ exists not exists();
}

答案 1 :(得分:1)

userDoc = userDoc.get();

在此行userDoc.get()返回一个承诺,并分配给userDoc。兑现诺言后,您将收到一个DocumentSnapshot,它将具有exists属性。

userDoc.get()
.then(doc=> {
    if(doc.exists) console.log(doc.data());
})

您可以查看文档中的examples,了解如何使用javascript SDK读取数据。