一旦所有的子快照都已执行,我想调用一个函数,
进一步阐述:
我有一个数据集假设-kvbd ... sd有两个子数据集
... -kvbd SD ----------> -fdvdv -... JH ----------> -fgshs..shsh
我想在为两个子节点完成处理后调用该函数
----------> -fdvdv -... JH ----------> -fgshs..shsh
我的代码:
...
$scope.getTitlesValues = function () {
return ['India','Australia', 'Germany', 'Sweden']
}
...
答案 0 :(得分:1)
您可以使用Promise
s尝试类似的内容:
ref.once('value')
.then(function(snapshot) {
var myFunctToRunAfter = function () {
console.info('RUN AFTER THE LOOP')
}
return new Promise(function(resolve, reject) {
snapshot.forEach(function(child) {
console.log('I am a child ' + child.val())
})
/* Call the function after the loop */
resolve(myFunctToRunAfter())
})
.then(function() {
/* I could do something here */
console.log(snapshot.val())
console.info('RUN LAST')
})
})
这是一个有效的例子:
var config = {
apiKey: "AIzaSyCDyoPVmi2rLIFtb55eTGYYPMsxFR3uuMs",
authDomain: "test-514b2.firebaseapp.com",
databaseURL: "https://test-514b2.firebaseio.com",
storageBucket: "test-514b2.appspot.com",
messagingSenderId: "773249287825"
};
firebase.initializeApp(config);
var ref = firebase.database().ref();
ref.once('value')
.then(function(snapshot) {
var myFunctToRunAfter = function () {
console.info('RUN AFTER THE LOOP');
}
return new Promise(function(resolve, reject) {
snapshot.forEach(function(child) {
console.log('I am a child ' + child.val())
})
/* Call the function after the loop */
resolve(myFunctToRunAfter())
})
.then(() => {
/* I could do something here */
console.log(snapshot.val())
console.info('RUN LAST')
})
})

<script src="https://www.gstatic.com/firebasejs/3.6.9/firebase.js"></script>
&#13;
Codepen使用相同的工作示例。