Firebase on()不返回任何内容 [英] Firebase on() does not return anything
问题描述
我有这段代码使用on()从Firebase中获取数据,在on()内部我创建了一个对象,该对象要从函数中发送出去以供将来使用-使用return,但似乎它不返回任何内容.那么问题是我该怎么做呢?
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;
});
推荐答案
回调函数被异步调用(在将来的某个时候).因此,在调用它时, postsRef.on(...)
已经返回,并且紧随其后的任何代码都将运行.
The callback function is called asynchronously (some time in the future). So by the time it is invoked, postsRef.on(...)
has already returned and any code immediately after it will have run.
例如,这可能很诱人,但不起作用:
For example, this might be tempting, but would not work:
var postsData;
postsRef.on('value', function(snapshot) {
postsData = snapshot.val();
});
console.log(postsData); // postsData hasn't been set yet!
因此,有几种不同的方法可以解决此问题.最佳答案将取决于首选项和代码结构:
So there are a few different ways to tackle this. The best answer will depend on preference and code structure:
将访问 postsData
的逻辑移到回调中
Move the logic accessing postsData
into the callback
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 */ );
这篇关于Firebase on()不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!