【发布时间】:2021-02-07 19:15:58
【问题描述】:
我正在尝试使用 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.
【问题讨论】:
-
如果您只需要检索数据,则不要使用 onSnapshot() 函数,而是使用 .get() 方法,那么异步等待可能会起作用。
-
您找到这个问题的答案了吗?我似乎遇到了类似的问题。
标签: javascript firebase google-cloud-firestore