本文介绍了Firestore,onSnapshot()或异步/等待问题或两者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Firebase Firestore的 onShapshot().

I'm trying to get an array of changes using Firebase Firestore's onShapshot().

我无法通过 onSnapshot()检索数据;我也可能会遇到 async/await 的麻烦,不太清楚...

I'm having trouble retrieving data through onSnapshot(); I may be in trouble with async/await as well, not quite sure...

您能看到哪里有问题吗?

Can you see where there are problems?

输出应为(但当前为)

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.

推荐答案

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

Have a look at this answer which explains the difference between the get() and onSnapshot() methods.

简而言之:

  • 当您使用 get()时,您仅会一次检索该集合的所有文档(如一劳永逸").
  • 使用 onSnapshot()时,您恒定收听该集合.
  • When you use get() you retrieve all the documents of the collection only once (like a "get and forget").
  • When you use onSnapshot() you constantly listen to the collection.

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

由于您的问题,看来您想通过调用 getAllFriends()方法来获取朋友列表,请执行以下操作:

Since, from your question, it seems that you want to get the list of friends by calling the getAllFriends() method, do as follows:

  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文档中,此处此处.

这篇关于Firestore,onSnapshot()或异步/等待问题或两者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 06:43