Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run something after get value from firebase javascript

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?

enter image description here

like image 780
Prateek Goyal Avatar asked Oct 15 '22 02:10

Prateek Goyal


1 Answers

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

like image 160
Subesh Bhandari Avatar answered Oct 18 '22 23:10

Subesh Bhandari