我希望每次刷新时都能随机加载所有 Firebase 内容,但我似乎无法将所有 Firebase 数据放入字典中进行随机化。
我有一个全局数组,我正在尝试将我的文件插入其中,然后迭代它们。但 Javascript 认为数组为空,因为计时已关闭。
var randomStore = new Array;
function homeSetup() {
if(ref.toString() == featuredRef.toString()){
addFeaturedImages();
}
console.log('randomStore length is ' + randomStore.length);
}
function addFeaturedImages(){
featuredRef.on("child_added", function(snapshot) {
var doc = {
// 'name': snapshot.key, //name is the id
'artist': snapshot.val().artist,
'author': snapshot.val().author,
'projectTitle': snapshot.val().projectTitle,
'text': snapshot.val().text
};
randomStore.push(doc);
console.log('randomStore length HERE is ' + randomStore.length);
});
}
考虑到代码的输入方式,我假设首先输入“randomStore length HERE is”日志,但我得到的是:
randomStore length is 0
randomStore length HERE is 1
randomStore length HERE is 2
randomStore length HERE is 3
如果我将数据放入不同的数组中,那么我可以对其进行随机排序之类的操作,但我似乎无法正确地将其放入其中。
最佳答案
你提到时机不对?你这是什么意思?
你听说过 Javascript Promise 吗?
http://www.html5rocks.com/en/tutorials/es6/promises/
这篇文章很好地解释了 promise 。请仔细阅读本文,因为如果您使用 Firebase,您将每日使用 Promise!
关于Javascript - 如何从 Google Firebase 随机提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772941/