![](/img/trans.png)
[英]Why Golang allows circular reference in global scope but not in function scope
[英]Data not working in global scope but in local scope
我一直在尝试制作一个电子商务网站,除了数据库部分之外,几乎所有的事情都完成了。 其中我必须从 firebase 获取数据并将其用于产品部分。 我已经在局部变量中获取了数据,但是我想将数据存储在全局范围的 object 中,但它不起作用。 所以我基本上想要的是我想从 firebase(DONE) 获取数据并将其存储在全局 scope 对象(PENDING) 中,以便我可以在 other.js 文件中使用这个 object。 任何类型的想法/建议/帮助/建议都非常受欢迎!! 提前致谢!
这是我的代码: https://jsfiddle.net/kumartanwar123/gseh4coq/
或者
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js";
// GLOBAL VARIABLES
var name, images, prices;
const firebaseConfig = {
apiKey: "--",
authDomain: "--",
databaseURL: "--",
projectId: "round-device-336118",
storageBucket: "round-device-336118.appspot.com",
messagingSenderId: "--",
appId: "--",
measurementId: "--",
};
const app = initializeApp(firebaseConfig);
firebase.initializeApp(firebaseConfig);
class firebase_class {
constructor(Images, Prices, Name) {
this.Images = Images;
this.Prices = Prices;
this.Name = Name;
}
}
// FIREBASE DATA FETCH
firebase
.database()
.ref("Practice")
.on("value", function (all_data) {
all_data.forEach(function (current_data) {
name = Object.keys(current_data.val().Name).map(
(keys) => current_data.val().Name[keys]
);
//In this if I use console.log(name) then it is working just fine, but not in outside the function.
images = Object.keys(current_data.val().Images).map(
(keys) => current_data.val().Images[keys]
);
prices = Object.keys(current_data.val().Prices).map(
(keys) => current_data.val().Prices[keys]
);
});
});
let firebase_object = new firebase_class(images, prices, name);
问题不在于访问数据库的位置,而在于访问数据库的时间。
数据从 Firebase(以及几乎所有现代云 API)异步加载,并且您的主要代码(因此let firebase_object = new firebase_class(images, prices, name)
)在加载数据时继续执行。 然后当数据可用时,您的回调将被调用并设置images
、 prices
和name
。
需要来自 Firebase 的数据的代码必须在回调中,或者从那里调用。 所以:
// FIREBASE DATA FETCH
firebase
.database()
.ref("Practice")
.on("value", function (all_data) {
all_data.forEach(function (current_data) {
name = Object.keys(current_data.val().Name).map(
(keys) => current_data.val().Name[keys]
);
//In this if I use console.log(name) then it is working just fine, but not in outside the function.
images = Object.keys(current_data.val().Images).map(
(keys) => current_data.val().Images[keys]
);
prices = Object.keys(current_data.val().Prices).map(
(keys) => current_data.val().Prices[keys]
);
});
// 👇
let firebase_object = new firebase_class(images, prices, name);
... any use of firebase_object should be here too
});
另请查看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.