0

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: 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);
Blerdijan
  • 27
  • 6

1 Answers1

1

Firestore documents are fetched asynchronously, so you'll need to either properly use Promises or use async/await. Here's one way you could rewrite the code to properly handle async:

  async function playerOne(){
    const doc = await db.collection("game").doc("8741").get();
    if (doc.exists) {
      return doc.data().playerone
    } else {
      // doc.data() will be undefined in this case
      console.log("No such document!");
    }
  }
  
  playerOne().then(b => console.log(b));

Understanding async code and function closures is going to be very important to being able to successfully build JavaScript apps, so I'd recommend you do some more reading and experimenting there!

Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
  • Hello thank you for dividing your time to help me! I tried this code of yours but I get this error: Uncaught SyntaxError: await is only valid in async function. And it tells me in line 42, where this code is: var b = await playerOne(); – Blerdijan Nov 24 '20 at 18:36
  • I edited my answer not to rely on top-level await. Try that? – Michael Bleigh Nov 24 '20 at 19:04
  • This works!!! thank you so much! But could you please explain how can I now store this into a variable for example var result, and use result later somewhere? because if i do now console.log("b") it gives me b is not defined – Blerdijan Nov 24 '20 at 19:09
  • 1
    You can assign to an outer variable from inside (so `.then(b => { result = b})`), but the key thing to remember is that the variable will be undefined until the async function completes, so you need to make sure you are properly waiting until it's set. – Michael Bleigh Nov 24 '20 at 19:30
  • Sir, thank you so much for helping me, now I have a more clear path and understand why i had the issue. – Blerdijan Nov 24 '20 at 20:06