I am trying to understand firebase-realtime-database. I am able to fetch the data, but I do not know how to add a completion block. I mean, is there a function to check when my data fetch query is completed?
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
}
Thank you very much!
CodePudding user response:
The once() method also returns a promise, so you can use the usual promise handling logic (then()/catch() or try/catch).
For example:
function getData() async {
let names = await firebase.database().ref('sections').once('value');
processData(names);
}
Update: since you now updated your code to show there are multiple once calls in a loop, you can use a Promise.all for that:
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);
});
});
}
