简体   繁体   中英

Attempting to read variables from Firebase with Javascript

I'm trying to access a simple Firebase database ( https://blazing-fire-6348.firebaseio.com ) and store its values separately, but they're not storing properly. The code below spits out all 10's, rather than the values stored in Firebase. I don't think my issue is just scope, but Firebase syntax. The tilde's are the website url, stackoverflow just wouldn't let me post the link multiple times.

Thanks for any help you can provide.

var a = 10; var b = 10; var c = 10;

var dataRef = new Firebase("~~~/a");
dataRef.on('value', function(snapshot) { 
   a = snapshot.val();
   // alert(a);
 });
var dataRef = new Firebase("~~~/b");
dataRef.on('value', function(snapshot) { if(snapshot.val() != null){
    b = snapshot.val();
   // alert(b);
} });
var dataRef = new Firebase("~~~/c");
dataRef.on('value', function(snapshot) { if(snapshot.val() != null){
    c = snapshot.val();
    // alert(c);
} });

alert(a); alert(b); alert(c);`

`

Your problem stems from the fact that the on call in Firebase is asynchronous:

var dataRef = new Firebase("~~~/a");
dataRef.on('value', function(snapshot) { 
    // this code will only execute once the server *returns* a value for a
});
// this code will execute straight after the call to the server has *started*

Your code will trigger three calls to the Firebase server, each of which can take some varying time to complete.

Therefore you cannot simply alert all three results at the end of the script and expect them to have the value from the server. All you know at the point in the script is that all calls to the server have started . There is no guarantee that any or all of them have completed though.

Instead you'll have to use a strategy to determine when all calls have completed.

A simple way to do this in your example:

var a, b, c;

var dataRef = new Firebase("~~~/a");
dataRef.on('value', function(snapshot) { 
   a = snapshot.val();
   if (a && b && c) alert(a+b+c);
 });
var dataRef = new Firebase("~~~/b");
dataRef.on('value', function(snapshot) { if(snapshot.val() != null){
    b = snapshot.val();
   if (a && b && c) alert(a+b+c);
} });
var dataRef = new Firebase("~~~/c");
dataRef.on('value', function(snapshot) { if(snapshot.val() != null){
    c = snapshot.val();
   if (a && b && c) alert(a+b+c);
} });

Each callback (the function that receives the snapshot, that you pass into on ) check whether the others have also completed. Only when all values have been set, will it alert their sum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM