Javascript 使用用户uid从firestore获取数据
我有个问题。 我需要从firestore获取数据,并希望将集合分配给我的变量,但函数不会等待完成firebase.auth,并在底部运行console.log。也许我在异步方面有问题。 我应该怎么做才能归还我的收藏? 我使用以下功能:Javascript 使用用户uid从firestore获取数据,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我有个问题。 我需要从firestore获取数据,并希望将集合分配给我的变量,但函数不会等待完成firebase.auth,并在底部运行console.log。也许我在异步方面有问题。 我应该怎么做才能归还我的收藏? 我使用以下功能: async function getDaySpending(period="7-2020"){ let arrayOfSpending=[]; await firebase.auth().onAuthStateChanged( funct
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
}
编辑
我不想开始一个新的话题,因为它是相关的。
我的代码:
我在控制台中得到如下响应:
“在初始化中”、“之后”、“空”、“用户处于活动状态”
但我希望得到这样的回应:
“用户处于活动状态”,“在初始化中”,用户数据改为空,“之后”
我该怎么办?
然后
和等待
做同样的事情。你不想把它们混在一起,一般来说,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-->返回用户。@Sebastian您只需确保在知道firebase auth已加载后调用
GetDayExpansing
。您在哪里以及如何调用GetDayExpensing
?是的,您是对的。我没有检查。我需要修理它
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
}
}