javascriptfunctiongoogle-cloud-firestorescopeglobal-scope

Bring variable value from Block to Global Scope (in FIRESTORE)


I'm creating an App in Firebase, using FireStore as my Database.

In the code below, I create a variable order and assign it a value of 1.

Then I update the value to the number 4 and console.log it to check. Which turns out fine.

But when I log the variable after the function, it returns 1 again, instead of the updated value.

This is My code (do See the //comments)

    console.log("Value initiated : " + order); // logs 'Value initiated : 1'

    //A function that gets another value from the FireStore Database and assigns it to the variable.
    function getField() {
      db.collection("index")
        .doc("artNum")
        .get()
        .then(function(doc) {
          order = doc.data().artNum; //I reassign the variable to '4' here.
          console.log("Value assigned : " + order); // logs 'Value assigned : 4'
        })
        .catch(err => {
          console.log(err);
        });
    }

    getField(); 
    console.log("Updated Value : " + order); // logs " Updated Value : 1 " but should be equal to 4 

Please help me with what I'm doing wrong or what this code is missing.


Solution

  • You can just do window.order = yourValue (replace window with global if you are in node) to create a global order variable.

    You also have to understand that your code is asynchronous which means that the updates will happen after your getField function is called. So looking for the new value will not work. However your getFields function returns a Promise that is always fulfilled (thanks to your catch clause).

    So this should work

    console.log("Value initiated : " + order); // logs 'Value initiated : 1'
    
    //A function that gets another value from the FireStore Database and assigns it to the variable.
    function getField() {
      return db.collection("index")
        .doc("artNum")
        .get()
        .then(function(doc) {
          order = doc.data().artNum; //I reassign the variable to '4' here.
          console.log("Value assigned : " + order); // logs 'Value assigned : 4'
        })
        .catch(err => {
          console.log(err);
        });
    }
    
    getField().then(() => console.log("Updated value", order));