你在这里引入了异步代码。
firestore.collection(`posts`).get().then((snapShot) => {
snapShot.docs.forEach((doc) => {
let data = { ...doc.data() };
posts.unshift(data);
});
});
get() 方法返回一个promise,一旦它被解析,它将在 .then() 方法中处理。这意味着,只有 then() 中的内容会等待其执行完成,并且块外的任何内容都会同步执行。
在您的情况下,所有 console.log() 方法都将在您实际从 Fire 基地获取数据之前执行。要修复它,您可以像 Peter 所说的那样操作 then() 方法中的数据,也可以使用 async/await。
例子:
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
const consoleIt = async () => { // returns a promise implicitly
value = await promise1;
console.log('value',value)
}
consoleIt(); // Expected output: "value" "foo"
//or
const consoleIt2 = async () => { // returns a promise implicitly
value = await promise1;
return value;
}
consoleIt2().then(value => console.log('value', value)); // Expected output: "value" "foo"
你的代码应该是:
const getPosts = async () => {
const posts = [];
let snapShot = await firestore.collection(`posts`).get(); // rest of the code will wait for the snapShot value.
snapShot.docs.forEach((doc) => {
let data = { ...doc.data() };
posts.unshift(data);
});
console.log(posts);
console.log(posts.length);
console.log(posts[1]); // Will print the object.
return posts;
};
异步函数通常返回 promise。你可以像这样调用这个函数
const posts = await getPosts();
要么
getPosts().then((posts)=> {console.log(posts)})
你的代码应该是这样的
const PostsList = () => {
getPosts().then((posts) => {
console.log(posts); // prints object
return posts.map((post) => <PostItem key={post.id} event={post} />); };
});
// or if you want to handle no data.
let posts = null;
const PostsList = () => {
getPosts().then((res) => {
post = res;
console.log(posts); // prints object
});
return posts? posts.map((post) => <PostItem key={post.id} event={post} />) : <NoData/>;
}
注意:await 关键字只能在异步函数中使用!