Javascript Firebase 实时数据库完成块
Javascript Firebase RealTime Database Completion Block
我正在尝试了解 firebase-realtime-database。我能够获取数据,但我不知道如何添加完成块。我的意思是,是否有检查我的数据提取查询何时完成的功能?
function getData() {
firebase.database().ref('SectionNames').once('value', function(names) {
names.val().forEach(function(sectionname) {
firebase.database().ref('Sections').child(sectionname).once('value').then( function(child)
//code
});
});
});
//Completion block or a method to call processData() after I get all the sections
}
function processData() {
//call this function after you get all the sections
}
非常感谢!
once()
方法也是 returns 一个承诺,因此您可以使用通常的承诺处理逻辑(then()
/catch()
或 try
/catch
).
例如:
function getData() async {
let names = await firebase.database().ref('sections').once('value');
processData(names);
}
更新:由于您现在更新了代码以显示循环中有多个 once
调用,因此您可以为此使用 Promise.all
:
function getData() {
firebase.database().ref('SectionNames').once('value', function(names) {
let promises = [];
names.val().forEach(function(sectionname) {
promises.push(
firebase.database().ref('Sections').child(sectionname).once('value')
);
});
Promise.all(promises).then((snapshots) => {
processData(snapshots);
});
});
}
我正在尝试了解 firebase-realtime-database。我能够获取数据,但我不知道如何添加完成块。我的意思是,是否有检查我的数据提取查询何时完成的功能?
function getData() {
firebase.database().ref('SectionNames').once('value', function(names) {
names.val().forEach(function(sectionname) {
firebase.database().ref('Sections').child(sectionname).once('value').then( function(child)
//code
});
});
});
//Completion block or a method to call processData() after I get all the sections
}
function processData() {
//call this function after you get all the sections
}
非常感谢!
once()
方法也是 returns 一个承诺,因此您可以使用通常的承诺处理逻辑(then()
/catch()
或 try
/catch
).
例如:
function getData() async {
let names = await firebase.database().ref('sections').once('value');
processData(names);
}
更新:由于您现在更新了代码以显示循环中有多个 once
调用,因此您可以为此使用 Promise.all
:
function getData() {
firebase.database().ref('SectionNames').once('value', function(names) {
let promises = [];
names.val().forEach(function(sectionname) {
promises.push(
firebase.database().ref('Sections').child(sectionname).once('value')
);
});
Promise.all(promises).then((snapshots) => {
processData(snapshots);
});
});
}