Javascript Firebase将数据库中的数据设置为变量
我刚开始使用Firebase,无法从数据库中获取数据。这是我的密码Javascript Firebase将数据库中的数据设置为变量,javascript,html,firebase,firebase-realtime-database,Javascript,Html,Firebase,Firebase Realtime Database,我刚开始使用Firebase,无法从数据库中获取数据。这是我的密码 const books = firebase.database().ref('Books'); var index; books.once("value", function(snapshot) { index = snapshot.val().Count }); console.log(index) 控制台日志提供未定义的。问题出在哪里?谢谢。您遇到的问题是那本书。once是异步的,所以您的代码中实际发生的事情是这样
const books = firebase.database().ref('Books');
var index;
books.once("value", function(snapshot) {
index = snapshot.val().Count
});
console.log(index)
控制台日志提供未定义的
。问题出在哪里?谢谢。您遇到的问题是那本书。once是异步的,所以您的代码中实际发生的事情是这样的
//set reference to books
//set variable index to undefined
//start a call to update index
//log the value of index
//call to update value finishes, index gets set to something
尝试将您的console.log移动到books.once块中,并查看是否记录了该值 您的调用是异步的,
console.log
会被执行,即使.once()
尚未完成
这样做:
books.once("value", function(snapshot) {
index = snapshot.key; // Count doesn't exist, the index is called "key" in firebase
return snapshot.val();
}).then(function(books) {
// This basically makes sure that the .once() callback has been done. Now you can see what's in `books`.
console.log(books);
});
编辑:您不能在异步操作之外访问书籍的.val()
这样做:
books.once("value", function(snapshot) {
index = snapshot.key; // Count doesn't exist, the index is called "key" in firebase
return snapshot.val();
}).then(function(books) {
// This basically makes sure that the .once() callback has been done. Now you can see what's in `books`.
console.log(books);
});
发生的情况是,数据是临时的,如果您尝试从Firebase函数外部读取“index”,则“index”将为空,并返回null,导致“undefined”,因此您需要将“console.log”函数放在“then(func())”函数中,或将变量集函数放在“once(action,func())函数中'函数。请尝试回调函数中的console.log(snapshot.val())并让我知道输出是正确的,但我需要将此值设置为全局值。有没有办法做到这一点?这取决于你如何定义全局。您可以查看async wait,也可以将then链接到调用之外,但不可避免地,您将不得不以某种方式等待调用完成