I implemented a function where I want to return an object saved under a certain url. In the code below, the first 'console.log(result);' returns the right object from the firebase location. The second one return undefined. Can somebody explain why and how to fix it?
_getById: function(obj) {
var url = "https://my-app.firebaseio.com/list/" + obj.groupId;
console.log(url);
var ref = new Firebase(url);
var result = {};
ref.on("value", function(snapshot) {
result = snapshot.val(); //first
console.log(result);
}, function (errorObject) {
}
);
console.log(result); //second
return result;
},
The data is loaded from Firebase asynchronously. So you'll notice that your second
console.log()
displays before the first one. You cannot return data that is being loaded asynchronously.You'll have to change the way you code. Instead of "get the id, then do something with it", you need to "do something whenever the id is loaded/changed".
So instead of:
You'll:
In the above code we're passing a callback into
_getById()
and invoke that callback when the list has loaded (and whenever the list changes).Some further reading material: