So I'm new to Javascript (mostly a Python person) and I'm having trouble understanding some really strange behaviors.
Long story short - I have an object in the databse (firebase firestore) that I'm trying to return. Right after I fetch it, I do a console.log and see the object in the console, and it's there! However when I return the same object...it shows as "noname" :(
Here is the code
function load_name() {
var db = firebase.firestore();
var name = "noname";
var docRef = db.collection("cities").doc("SF");
docRef.get().then(function (doc) {
if (doc.exists) {
name = doc.data().name;
//following shows as 'San Francisco' in console
console.log(name);
return name; //Added this line later to see if issue is fixed, but it didn't fix it.
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}
).catch(function (error) {
console.log("Error getting document:", error);
});
return name;
}
myname = load_name();
//^prints 'San Francisco' on console, but returns as undefined.
I've spent about 5 hours on this. Any help would be appreciated!