我有一个函数触发两个“值”Firebase 事件。需要先获取children的数量,对应下一个的最深路径。
function myFunction(data){
//get last child
var lastchild = 0;
var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
data_child.once('value', function(child) {
if(child.exists()){
lastchild = child.numChildren();
console.log('function 1');
}else{
console.log('error no child');
}
});
//use this number to read the path
var msgsStored = firebase.database().ref('rooms/' + 633 + '/' + 630 + '/' + lastchild);
msgsStored.orderByChild('datetime').once('value', function(snapshot) {
var store = (snapshot.val());
snapshot.forEach(function(child) {
console.log('function 2');
//do something
}
}
}//myFunction
Firebase 始终会在第一个事件之前触发最后一个“值”事件。为什么? 这将导致变量lastchild = 0;在控制台上,“function 2”将始终在“function 1”之前打印。 我也尝试创建一个回调();函数尝试用 JavaScript 控制顺序,但不起作用。 我知道 Firebase 的不同事件以不同的顺序触发,但就我而言,我只需要读取存储的数据。 有人知道我缺少什么以及如何向我提供解决方案吗?
最佳答案
Firebase 与大多数现代网络一样,从数据库中异步读取数据。通过在代码中放置一些日志语句最容易看到这一点:
console.log("1");
var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
data_child.once('value', function(child) {
console.log("2");
});
console.log("3");
其输出是:
1
3
2
这可能不是您最初所期望的,但可以解释您所看到的行为的很多内容。当日志语句3执行时,来自第一个监听器的数据尚未加载。因此您无法根据该数据进行查询。
因此,您始终需要将需要数据的代码移至回调中:
var lastchild = 0;
var data_child = firebase.database().ref('rooms/' + 633 + '/' + 630);
data_child.once('value', function(child) {
if(child.exists()){
lastchild = child.numChildren();
//use this number to read the path
var msgsStored = firebase.database().ref('rooms/' + 633 + '/' + 630 + '/' + lastchild);
msgsStored.orderByChild('datetime').once('value', function(snapshot) {
var store = (snapshot.val());
snapshot.forEach(function(child) {
console.log('function 2');
//do something
}
}
}else{
console.log('error no child');
}
});
关于javascript Firebase 如何按顺序触发 'value' 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47166616/