我有一个javascript函数,可以从firebase实时数据库中的一个节点获取一些值。JS代码为:
var numZones;
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var db = firebase.database();
var ref = firebase.database().ref("/LH121");
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
});
console.log('After get value');
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.3/firebase-database.js"></script>
<div class="container" style="text-align: center;">
<div class="row">
<input type="number" name="zones" id="zones" step="1">
</div>
</div>
当从firebase获取值完成时,我想要访问一些东西。我如何做到这一点呢?
发布于 2020-06-25 21:02:10
因为.once
返回一个promise,所以您可以链接一个.then
块,以便在.once
执行之后运行您想要的代码。
参考:https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
ref.child("NumZones").once('value', function(snapshot)
{
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
我建议您使用以下代码,而不是在.once
上传递回调函数。
ref.child("NumZones").once('value').then((snapshot) => {
numZones = snapshot.val();
document.getElementById("zones").value = numZones;
console.log('Got value');
}).then(() => console.log("After get value"));
有关javascript promises的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://stackoverflow.com/questions/62575817
复制相似问题