将变量分配给Firestore值检查

时间:2020-10-03 12:26:28

标签: javascript firebase google-cloud-firestore async-await

我正在尝试将bm_array分配给我的Firestore数组(如果存在,则为空数组)。 逻辑是检查名称为当前用户Firebase uid的Firestore文档。我可以console.log我想要的数组(在第12行),但是在实际数组分配给bm_array之前,null返回bm_array(在第25行)。我尝试使用异步,但bm_array返回诺言对象或为null。我不确定如何使用异步。

var bm_array = null;
const getBookmarks = async() => {
  var firestore = firebase.firestore();
  var userBookmarks = firestore.collection("userBookmarks");
  await firebase.auth().onAuthStateChanged(async function(user) {
    if (user) {
      // User is signed in.
      var user = firebase.auth().currentUser;
      await userBookmarks.doc(user.uid).get().then(async function(doc){
        if (doc.exists){
          bm_array = await doc.data().countries;
          console.log(bm_array);
        }else{
          bm_array = [];
        }
      }).catch(function(error) {
        console.log("Error getting document:", error);
      });
    } else {
      return []
    }
  });
 }
 getBookmarks();
 console.log(bm_array);

1 个答案:

答案 0 :(得分:2)

onAuthStateChanged()“添加观察者以更改用户的登录状态”。因此,可以恒定观察用户的登录状态是否正在更改。

由于要通过调用函数执行业务逻辑,因此最好使用currentUser属性来获取用户价值。

以下几行应该可以解决问题:

  const getBookmarks = async () => {
    var firestore = firebase.firestore();
    var userBookmarks = firestore.collection('userBookmarks');
    
    const user = firebase.auth().currentUser;
    
    if (user) {
        const docSnapshot = await userBookmarks
          .doc(user.uid)
          .get();
          // Note that you need to use await only in the above line, since it is the only asynchronous operation in your async function              

          if (docSnapshot.exists) {
              bm_array = docSnapshot.data().countries;
          } else {
              bm_array = [];
          }
      } else {
          // Not sure you should return anything here,
          // since you just call the function as getBookmarks(); without using the potential returned value
          // Note that you don't return anything when user is not undefined, i.e. in the first part of the if block, above
        return [];
      }
    
  };