0

My current code for accessing my Firebase databse from Node.js looks roughly like this.:

var DesiredValue = "#";
ref.child("Example").once("value", function(snapshot) {
  DesiredValue = snapshot.val();
  console.log(DesiredValue)
});
console.log(DesiredValue)

It returns

>42
>#

where 42 is the value I want to grab, but I can't figure out how to retrieve it outside the scope of ref.child.(). I have tried the following which doesn't work.

var DesiredValue = ref.child("Example").once("value", function(snapshot) {
  var DesiredValue = snapshot.val();
  console.log(DesiredValue)
  return DesiredValue
});
console.log(DesiredValue)

All I want to do is use 42 in the remainder of the code. Based on what I have read there might be some way of using JavaScript's 'this' to achieve my goal, but I am worried of messing with global variables and think there must be an easier way?

AJGronevelt
  • 551
  • 1
  • 6
  • 22
  • you want to use this value in one flow of execution or sometime later aswell? issue is your outside console.log calls before the once callback but it should print # first in the console then 42 – Asif Saeed Jan 28 '17 at 15:54

1 Answers1

0

It's a callback you may use a promise, when it is resolved then you can use the value out of function or handle the value inside the callback, otherwise the code it's executed without waiting

jesusgn90
  • 563
  • 2
  • 12