1

I'm just trying to perform a simple firebase data retrieval. Here's what I have

var fb = new Firebase("https://<my-app>.firebaseio.com");

fb.on('value', function(snapshot) {
  var db = snapshot.val();
  var speed = db['speed'];
 });

console.log(speed);

rnd = Math.floor( Math.random() * 7 );
fb.set({ speed: rnd});

The problem I have is speed is stuck inside of the fb.on area. How do I get it out of there?

Matt Coady
  • 3,418
  • 5
  • 38
  • 63

1 Answers1

3

Your code isn't getting stuck, you're calling it incorrectly.

fb.on('value', function(snapshot) {
  var db = snapshot.val();
  var speed = db['speed'];
});

Here you're providing a callback function with a local variable speed. This variable will probably be set correctly, but you're not doing anything with it.

console.log(speed);

rnd = Math.floor( Math.random() * 7 );
fb.set({ speed: rnd});

This code runs straight after you've set up the event handler (fb.on( 'value', ... )) but that code runs asynchronously. Not only will that function probably not have ran at this point, but here you are accessing an undeclared variable speed, and because it isn't declared it is an automatic global variable window.speed, and not the local variable speed in the callback function.

Move the console.log inside of the callback function to execute it at the right time. Also, always declare your variables.

Leeft
  • 3,827
  • 1
  • 17
  • 25