Returning undefined object from a firebase snapshot

你说的曾经没有我的故事 提交于 2019-12-11 12:42:53

问题


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;
    },

回答1:


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:

  • Polymer Firebase: Print async data
  • Asynchronous access to an array in Firebase
  • Trying to get child records from Firebase
  • Handling Asynchronous Calls (Firebase) in functions


来源:https://stackoverflow.com/questions/31949146/returning-undefined-object-from-a-firebase-snapshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!