1

I am trying to access the rate variable from outside the function in which it is defined. I have declared a global rate variable but it is "undefined" at the point I need to use it. I've minimized the code to keep it as clean as possible.

var db = firebase.firestore();
var docRef = db.collection("pricing").doc("default");

var rate; //Setting up global variable to store value

docRef.get().then(function(doc) {
        console.log("Document data:", doc.data().base); //This works
        rate = doc.data().base;
        console.log("Rate:", rate); //This works
    });

console.log("Rate:", rate); //rate is "undefined" but rate variable value
//is accessible if typed via the console?
ebbishop
  • 1,833
  • 2
  • 20
  • 45
Noob
  • 43
  • 6
  • Your `console.log` on the last line gets executed before `get()` is resolved. You should read up on promises and how JavaScript handles asynchronous code to learn more about this behavior. – Wex Oct 07 '20 at 20:00
  • Thank you Wex, I will read up on this but any steer as to the code changes I can use to make this work? – Noob Oct 07 '20 at 21:46

3 Answers3

1

docRef.get() is asynchronous and returns immediately, before the query is complete. You use that promise to attach a callback function using then that gets invoked some time later. Meanwhile, your code will continue to execute. What you are observing is that the console log is running before rate gets defined in the callback.

You will have to adjust things so that your code that depends on rate being defined must only execute after the callback. This typically means that you write the code inside the callback, or using another callback.

It's strongly advisable to learn how JavaScript promises work, as they are critical to writing effective code.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

rate is being assigned inside then block, which is executed when Promise, returned from docRef.get() will be resolved. So at the moment of calling console.log, as of then block executes asynchronously, rate is not assigned yet.

Niki-Timofe
  • 105
  • 1
  • 6
0

It's a race condition: rate is assigned when the promise returns--after your console.log.

You could set your code up to run synchronously; then, the console.log will not run until after the data have been returned:

Firebase Firestore retrieve data Synchronously/without callbacks

Note that this is generally not recommended, as it can negatively affect performance and UX. Pay close attention, and you may notice a short lock-up of the interface. Regardless, per your OP, since you are a "newbie," this may help you here for learning and testing.

kmiklas
  • 13,085
  • 22
  • 67
  • 103