将变量分配给 firestore 值检查

我正在尝试分配bm_array给我的 firestore 数组(如果存在,则为空数组)。逻辑是检查名称为当前用户 firebase uid 的 firestore 文档。我能够 console.log 我的预期数组(第 12 行),但是在实际数组分配给之前bm_array返回(第 25 行) 。我尝试使用异步,但 bm_array 要么返回一个 promise 对象,要么返回 null。我不确定如何使用异步。nullbm_array


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);


汪汪一只猫
浏览 95回答 1
1回答

至尊宝的传说

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 [];      }      };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript