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
use let instead of var
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