I've been trying to read about async functions and promises all day but I can't seem to wrap my head around retreiving the data in my example.
I have the following async function that iterates through some database values and appends them to an array which it returns:
async function userMemberships (){
var membershipsList = [];
onAuthStateChanged(auth, user => {
if(user){
var i= 0;
var refInstanceMemberships = ref(db, 'instance-memberships/');
onValue(refInstanceMemberships, (instanceMembershipsSnap) => {
instanceMembershipsSnap.forEach((instanceSnap) => {
instanceSnap.forEach((userSnap) => {
if(userSnap.key == user.uid){
membershipsList.push(
{instanceId: userSnap.ref.parent.key}
//userSnap.ref.parent.key
)
//appendToInstanceList(userSnap.ref.parent.key)
}
})
})
}, {
onlyOnce: true
})
} else{
console.log('Not logged in...');
}
});
return membershipsList
}
From what I understand, because this is an async function, it is going to return a promise, and for me to get the array values I need to call this function from another async function along with 'await'. so I have the following function which does that:
async function getMemberships() {
const memberships = await userMemberships();
console.log(memberships) //Returns an array in the console log. Expected
console.log(memberships.length) //Returns 0. Unexpected
console.log(memberships[0]) //Returns undefined. Unexpected
}
This function is called using:
(async () => {await getMemberships()})();
I'm obviously missing something about async functions, because I thought that console.log(memberships.length)
would run after const memberships
had been populated, especially considering console.log(memberships)
did. Would anybody be able to try to explain this to me?