gpt4 book ai didi

javascript - 如何在 childsnapshot 完成执行后调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 16:02:50 24 4
gpt4 key购买 nike

我想在所有子快照执行完毕后调用一个函数,

进一步阐述:

我有一个数据集假设 -kvbd...sd 它有两个子数据集

-kvbd...sd ----------> -fdvdv-...jh ----------> -fgshs..shsh

我想在两个子节点处理完成后调用该函数

----------> -fdvdv-...jh ----------> -fgshs..shsh

我的代码:

dRef
.once("value")
.then
(
function(snapshot)
{

snapshot.forEach(
function(childsnapshot)
{
var data=childsnapshot.val();
var Apdate=data.Dateval;


for (i = 0; i < sel.options.length; i++)
{
var datein=sel.options[i].value;
console.log("check:"+datein);
if(datein==Apdate)
sel.options[i].disable = true;
console.log("Success:!!!!!!");
}
pass();


}
}
}
);

最佳答案

你可以用Promises尝试这样的事情:

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>

Codepen具有相同的工作示例。

关于javascript - 如何在 childsnapshot 完成执行后调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42137444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com