[英]Data collection from firebase firestore in react native returns undefined outside of promise
This method is supposed to return a list of users but returning an empty array.此方法应该返回用户列表,但返回一个空数组。 When I console log inside the forEach loop, it prints the data but not outside of it.
当我在 forEach 循环内进行控制台日志时,它会打印数据但不在其外部。
get getAllUsers() {
const usersList = [];
firebase
.firestore()
.collection('users')
.get()
.then(snapshot => {
snapshot.forEach(user => {
usersList.push(user.data());
console.log(user.data());
});
});
return usersList; // Array [] or undefined when indexed
}
On Home.js, I call it here.在 Home.js 上,我称之为这里。
componentDidMount() {
const list = fireStoreDB.getAllUsers;
console.log(list);
}
Array [] is the console log of the method and the objects are the console log from the forEach loop.数组 [] 是方法的控制台日志,对象是来自 forEach 循环的控制台日志。
You got an empty array, because your function is synchronous and firebase returns a promise which is asynchronous.你有一个空数组,因为你的 function 是同步的,而 firebase 返回一个异步的 promise。 So that's why in most cases you will get an empty array first, and after that response from firebase.
所以这就是为什么在大多数情况下你会首先得到一个空数组,然后是 firebase 的响应。
Try this one:试试这个:
async getAllUsers() {
const usersList = await firebase
.firestore()
.collection('users')
.get()
.then(snapshot => {
return snapshot.map(user => user.data(););
});
return usersList;
}
And then in Home.js然后在 Home.js
componentDidMount() {
fireStoreDB.getAllUsers().then(list => console.log(list));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.