Reputation: 47
I have a problem. I need to get data from firestore, and want to assign collection to my variable, but the function doesn't wait to finish firebase.auth,and run console.log at the bottom. Maybe I have a problem with async. What should I do to return my collection? I use the function:
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
}
EDIT I don't want to start a new topic, because it is related. My code:
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
}
}
I got a response in the console like: "in init","after","null","user is active" but I want to receive a response like : "user is active", "in init", user data instead null,"after";
What should I do?
Upvotes: 0
Views: 890
Reputation: 18612
then
and await
do the same thing. You don't want to mix them up, and generally speaking, await
is the newer more cleaner way of handling async functions, so you should pretty much always use await
whenever possible.
You can rewrite the code to something like this, but I was not sure what you want to return at the end:
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
}
}
Upvotes: 1