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, to cross-check, it returns 1 again, instead of the updated value(i.e. 4).
I want to use the value I'm getting from the database, in the global namespace. (use it simply in my JS code outside this function.)
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); // (to crosscheck) logs " Updated Value : 1 " but should be equal to 4
I've been into JS for only a month, I'm quite a beginner. Some of the solutions I thought-&-tried were.
- Use
order
variable outside the function straight-away, like I did above, which didn't work. - Assign the value of
order
to a new variable in the global namespace, which didn't work either.
I want to use this value outside in my global namespace.
Basically, I want to use the order
variable outside, in my code. Also, I'll use this variable again, for naming other documents in my Firestore Database. In simple terms, It's necessary for me to have this value as a simple global var
variable in my script.
Please help me with what I'm doing wrong or what this code is missing.