从 firebase 快照返回未定义的对象

Returning undefined object from a firebase snapshot

我实现了一个函数,我想 return 某个对象保存在某个 url 下。在下面的代码中,第一个 'console.log(result);' return 是来自 firebase 位置的正确对象。第二个 return 未定义。有人可以解释为什么以及如何解决它吗?

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

数据是从 Firebase 异步加载的。所以您会注意到第二个 console.log() 显示在第一个之前。您不能 return 正在异步加载的数据。

您必须改变编码方式。您需要 "do something whenever the id is loaded/changed".

而不是 "get the id, then do something with it"

所以代替:

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

您将:

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

在上面的代码中,我们将回调传递给 _getById() 并在列表加载后(以及列表更改时)调用该回调。

进一步阅读material:

  • Asynchronous access to an array in Firebase
  • Trying to get child records from Firebase
  • Handling Asynchronous Calls (Firebase) in functions