Firestore,onSnapshot()或异步/等待问题或两者

时间:2020-10-25 08:29:19

标签: javascript firebase google-cloud-firestore

我正在尝试使用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 个答案:

答案 0 :(得分:1)

看看这个answer,它解释了get()onSnapshot()方法之间的区别。

简而言之:

  • 使用get()时,您仅会一次检索该集合的所有文档(就像“忘记了”)。
  • 使用onSnapshot()时,您不断收听收藏集。

请注意,onSnapshot()不是异步方法,而get()是=>请勿使用onSnapshot()调用await


由于您的问题,看来您想通过调用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中可以找到更多的可能性。