问题描述
我无法访问从 Firestore 快照保存的数组的内容。
代码如下:
function getDataFromFirestore() {
let myList = [];
db.collection("test")
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
myList.push(doc.data());
});
});
console.log(myList);
console.log(myList[1]);
console.log(myList.length);
}
getDataFromFirestore();
这里是 console.log() 的返回:
问题: 为什么使用 forEach 将 3 个项目保存在数组中,并且长度为 = 0?
如何访问保存在数组中的对象?
非常感谢您的帮助。
解决方法
db.collection("test").get()
返回一个 promise,这意味着在最后的 console.logs 之后执行。
解决方案可能是将 console.logs 移到里面,或者使用 async await。