I have an issue where I want to get a value from my Firestore database and store it to a variable. All this process should happen inside a function.
However, when I try to return the result and call the function I get undefined
in the console. But if I try console.log the value instead of returning I actually get the result that I want in the console?
I did my research and I found out that I have to do with asynchronous request. I read this particular answer https://stackoverflow.com/a/14220323/13540535 but I was not able to implement the solutions that Mr. Felix Kling told us.
How can I solve this and where in my code should I use async/await
?
First, here is my Firestore database:
And here is my code where I get undefined:
var userScore = 0;
var compScore = 0;
const userResult = document.getElementById("user-score");
const compResult = document.getElementById("computer-score");
const resultText = document.getElementById("pharagraph");
const rockButton = document.getElementById("r");
const paperButton = document.getElementById("p");
const scissorsButton = document.getElementById("s");
const joinButton = document.getElementById("joinid");
var firebaseConfig = {
MY FIRESTORE CONFIG..
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
function playerOne(){
db.collection("game").doc("8741").get().then((doc) => {
if (doc.exists) {
// here I get undefined
var p = doc.data().playerone;
return p;
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
})
.catch(function (error) {
console.log("Error getting document:", error);
});
}
var b = playerOne();
console.log(b);