I'm fairly new to JavaScript, and I'm finding the concept of promises and "then" statements really hard to pin down. I'm working on a website using Firebase, and I'm trying to get user data from the database. Here's what I have at the moment:
// Function that fetches a user's data from the database.
getUserData = function(uid) {
var database = firebase.firestore();
var docRef = database.collection('users').doc(uid);
var userData = docRef.get().then(function(doc) {
if (doc.exists) {
return doc.data();
} else {
console.log("User does not exist.");
return null;
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
return userData;
}
Currently, this function returns a Promise object. When I log the object to the console, it says that the promise status is resolved and its value is the value of doc.data(). What I really want is to pass the value of doc.data() back up the "chain" to the getUserData function so that I can return and use it elsewhere. Is there a simple way to do this? I've tried to find a way to get the "value" of a Promise out of the object itself, but I've found nothing, and so far I have failed to find any other way to do what I want.
I'm sure it's a lot simpler than it seems, and I feel like an idiot for asking this sort of thing, but I've been searching for a couple of hours and none of the explanations I've found are helping. I would greatly appreciate any advice. Thanks!
Edit: Solved! Thanks for the help, everyone! Just in case this helps someone in the future who stumbles upon it, I'm leaving my final (working) code here. Unfortunately there's no way to call it from a synchronous function, but it ended up being good enough for my purposes:
// Function that fetches a user's data from the database.
async function getUserData(uid) {
var database = firebase.firestore();
var docRef = database.collection('users').doc(uid);
var doc = await docRef.get();
if (doc.exists) {
return doc.data();
} else {
console.log("User does not exist.");
return null;
}
}