【问题标题】:Get data from firestore by using user uid使用用户 uid 从 firestore 获取数据
【发布时间】:2021-04-10 17:09:30
【问题描述】:

我有问题。 我需要从 firestore 获取数据,并希望将集合分配给我的变量,但该函数不会等待完成 firebase.auth,并在底部运行 console.log。也许我有异步的问题。 我应该怎么做才能退回我的收藏? 我使用函数:

async function getDaySpending(period="7-2020"){
  let arrayOfSpending=[];
 await firebase.auth().onAuthStateChanged( function(user) {
    if (user) {
    firebaseApp.firestore().collection(user.uid).doc(period).get().then(doc=>{
        if(doc.exists){
          
     arrayOfSpending=doc.data().spending;       //assign value
     console.log(arrayOfSpending)     //return proper collection,run second
        }})
    } 
  }); 
console.log(arrayOfSpending);  //return null,run first
return arrayOfSpending
}

编辑 我不想开始一个新的话题,因为它是相关的。 我的代码:

init()

async function init () {
     await userIsActive()
    console.log("in init");     
  await getDaySpending();
    console.log("after") */
    
}

function userIsActive(){
    firebaseApp.auth().onAuthStateChanged( user=>{
    if(user){
      console.log("user is active");
      return true
    }else{
      console.log("no user");
      return false
    }
  })
  }

 function getDaySpending(period = '7-2020') {
    const user = firebase.auth().currentUser;
    if(!user) return;      //I got null instead user data
    const uid = user.uid;
    const snap  = await  firebase.firestore().collection(uid).doc(period).get();
    if(snap.exists) {
      return snap.data().spending;
    } else {
      // handle the case where there was no data
    }
  }

我在控制台中收到如下响应: "in init","after","null","user is active" 但我想收到如下回复: "user is active", "in init", user data instead null,"after";

我该怎么办?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    thenawait 做同样的事情。您不想混淆它们,一般来说,await 是处理异步函数的更新更简洁的方法,因此您应该尽可能始终使用await

    你可以把代码改写成这样,但我不确定你最后要返回什么:

    async function getDaySpending(period = '7-2020') {
        const user = firebase.auth().currentUser;
        if(!user) return; // if user is not signed in, return or do whatever you want to here
        const uid = user.uid;
        const snap  = await  firebase.firestore().collection(uid).doc(period).get();
        if(snap.exists) {
          return snap.data().spending;
        } else {
          // handle the case where there was no data
        }
      }
    

    【讨论】:

    • 我试过这种方式,但是函数firebase.auth().currentUser-->返回null。我需要使用 onAuthStateChanged --> return user.
    • @Sebastian 您只需要确保在知道 Firebase 身份验证已加载后调用 getDaySpending。你在哪里以及如何打电话给getDaySpending
    • 是的,你是对的。我没有检查它。我需要修复它
    猜你喜欢
    • 2020-09-12
    • 2019-07-03
    • 2021-02-09
    • 2019-06-18
    • 2019-05-28
    • 2017-08-19
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多