skip to Main Content

This line of code is getting document count from firestore database it works fine when i call the variable inside the function but outside its undefine.

 var LM35TOTALRES; // I WANT TO STORE HERE

    db.collection("LM35").get().then(function(querySnapshot) {      
    
        LM35TOTALRES = querySnapshot.size //DATA THAT I WANT
         
    console.log(LM35TOTALRES); // THIS IS WORKING       
    });
    console.log(LM35TOTALRES); // NOT WORKING 

2

Answers


  1. use let instead of var

    let LM35TOTALRES;
    
    Login or Signup to reply.
  2. I believe this is because the function is async so it finishes setting the value after the log outside, One solution is to return the value needed in the variable directly and await it like so const LM35TOTALRES = await (db.collection("LM35").get()).size

    This occurs due event loop scheduling you can find some good examples in this video about min 2 or so

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search