I am having a javascript function that gets some value from a node in firebase realtime database. The JS code is:
var numZones;
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.database();
var ref = firebase.database().ref("/LH121");
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
});
console.log('After get value');
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-database.js"></script>
<div class="container" style="text-align: center;">
<div class="row">
<input type="number" name="zones" id="zones" step="1">
</div>
</div>
I want to access something when the get value from firebase is done. How can I do so?
Since .once
returns a promise you can chain a .then
block to run the code that you want after the .once
has been executed.
Reference: https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
I would suggest you to use the following instead of passing a callback function on .once
.
ref.child("NumZones").once('value').then((snapshot) => {
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
More about javascript promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With