1

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;
    },
Salah Saleh
  • 765
  • 9
  • 28

1 Answers1

2

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:

 var list = _getById({ groupId: 42});
 console.log("Our list is: "+list);

You'll:

 _getById({ groupId: 42 }, function(list) {
   console.log("Our list is: "+list);
 });
_getById: function(obj, callback) {
    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
        callback(result);
    }, function (errorObject) {
    });
    console.log(result); //second
    return result;
},

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:

Community
  • 1
  • 1
Frank van Puffelen
  • 418,229
  • 62
  • 649
  • 645