我尝试使用Firebase Firestore的onShapshot()获取一系列更改。
通过onSnapshot()
检索数据时遇到问题;我可能也遇到了async/await
的麻烦,不太确定...
你能看出哪里有问题吗?
输出应该是(但目前是):
1. New friends: ... // via onSnapshot(). Should not be empty, but it is (However, it does get populated afterwards).
2. All friends: ... // Should not be empty, but it is.
3. Fred's friends: ... // Should not be empty, but it is.
验证码:
const getAllFriends = async () => {
// Gets all friends by connecting to Firestore's onSnapshot stream.
const getNewFriends = async () => {
// Sets up a onSnapshot() stream, and returns a newFriends array with their names.
// Problem: It initially return an empty array, when it shouldn't be empty.
let newFriends = [];
await db.collection("user").doc("john").collection("friends").onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
newFriends.push({ friend: "Emily" });
});
});
console.log("1. New friends: ", newFriends, newFriends.length); // Length should not be 0.
return newFriends;
}
// John starts with no friends:
let friends = [];
// John should now have found some friends:
let friendChanges = await getNewFriends();
friends = friends.concat(friendChanges);
console.log("2. All friends:", friends); // Should contain a few Emilys.
return friends;
};
let johnFriends = await getAllFriends();
console.log("3. John's friends:", friends); // Should contain a few Emilys.
1条答案
按热度按时间qybjjes11#
看看这个答案,它解释了
get()
和onSnapshot()
方法之间的区别。简而言之:
get()
的时候,你只需要检索集合中的所有文档一次(就像“get and forget”)。onSnapshot()
时,你会不断地收听集合。注意
onSnapshot()
不是异步方法,而get()
是=〉不要用await
调用onSnapshot()
。从您的问题来看,您似乎希望通过调用
getAllFriends()
方法来获取好友列表,请执行以下操作:在Firestore文档中可以找到更多的可能性,here和here。