3

I have this piece of code using on() to get data from Firebase, inside on() I create object which I want to send out of function for future use - using return, but it seems it doesn't return anything. So question is how can I make it right?

postsRef.on('value', function(snapshot) {
 if (snapshot.val() === null) {
  var allPosts = false,
  numberOfPosts = 0;
 }
 else {
  var allPosts = snapshot.val(),
  numberOfPosts = Object.size(allPosts);
 }
 var postsData = {
  content: allPosts,
  count: numberOfPosts
 };
 return postsData;
});
4

1 回答 1

6

回调函数被异步调用(在将来的某个时间)。因此,当它被调用时,postsRef.on(...)它已经返回并且任何代码都将立即运行。

例如,这可能很诱人,但不会起作用:

var postsData;
postsRef.on('value', function(snapshot) {
    postsData = snapshot.val();
});
console.log(postsData); // postsData hasn't been set yet!

所以有几种不同的方法来解决这个问题。最佳答案将取决于偏好和代码结构:

将逻辑访问postsData移到回调中

postsRef.on('value', function(snapshot) {
    postsData = snapshot.val();
    console.log(postsData);
});

调用回调时调用另一个函数

function logResults(postsData) {
   console.log(postsData);
}

postsRef.on('value', function(snapshot) {
    logResults(snapshot.val());
});

触发事件

function Observable() {
   this.listeners = [];
}

Observable.prototype = {
   monitorValue: function( postsRef ) {
      var self = this;
      postsRef.on('value', function(snapshot) {
         self._notifyListeners(postsRef);
      });
   },

   listen:  function( callback ) {
      this.listeners.push(callback);
   },

   _notifyListeners: function(data) {
      this.listeners.forEach(function(cb) {
         cb(data);
      }
   }
};

function logEvent( data ) {
   console.log(data);
}

var observable = new Observable();
observable.listen( logEvent );
observable.monitorValue( /* postsRef goes here */ );
于 2013-09-30T14:55:09.050 回答