firebase Firestore、onSnapshot()或async/await问题,或两者都有

but5z9lq  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(92)

我尝试使用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.
qybjjes1

qybjjes11#

看看这个答案,它解释了get()onSnapshot()方法之间的区别。
简而言之:

  • 当你使用get()的时候,你只需要检索集合中的所有文档一次(就像“get and forget”)。
  • 当你使用onSnapshot()时,你会不断地收听集合。

注意onSnapshot()不是异步方法,而get()是=〉不要用await调用onSnapshot()
从您的问题来看,您似乎希望通过调用getAllFriends()方法来获取好友列表,请执行以下操作:

const getAllFriends = async (userName) => {
    const querySnapshot = await db
      .collection('user')
      .doc(userName)
      .collection('friends')
      .get();
    return querySnapshot;
  };

  let johnFriends = await getAllFriends('john');
  johnFriends.forEach(doc => {
    console.log(doc.id, ' => ', doc.data());
  });

在Firestore文档中可以找到更多的可能性,herehere

相关问题