Я пытаюсь получить массив изменений с помощью 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.