首页 > 解决方案 > How to return data from Firestore promise?

问题描述

I have this code, which returns the parents of a certain doc. console.log(doc.ref.parent.get()) I use collectionGroup to search if there is user wit email which is same as the email of the user who is logged to the app.

var nameRef = db
    .collectionGroup('Users')
    .where('email', '==', currentUser.email)

  useEffect(() => {
    nameRef.get().then((snapshot) => {
      snapshot.docs.forEach((doc) => {
        console.log(doc.ref.parent.get())
      })
    })
  }, [])

It returns a promise:

enter image description here

How to Access the segments Array in the Path in the qf in PromiseResult. I tried some object restructuring but it did not work.

标签: javascriptfirebasegoogle-cloud-firestorepromise

解决方案


There are several problems in your code:

#1/ You don't return anything in your useEffect function.

#2/ doc.ref.parent.get() is asynchronous and will return immediately with a promise. The problem is that the forEach() loop will not wait for those promises to be fulfilled. See more explanations here. One classical solution is to use Promise.all() as shown below.

#3/ Last but not least, note that your useEffect function is asynchronous.

So, the following should do the trick:

  var nameRef = db
        .collectionGroup('Users')
        .where('email', '==', currentUser.email);

  useEffect(() => {
        return nameRef.get().then((snapshot) => {
            const promises = [];
            snapshot.docs.forEach((doc) => {
                promises.push(doc.ref.parent.get());
            });
            return Promise.all(promises);
        });
  }, []);

  // Call the function as follows, with a then() block or use the async/await keywords
  useEffect().then((results) => {   // results is an Array of DocumentSnapshots
    results.forEach((r) => {
      console.log(r.get('segments')); 
    });
  }); 
  

推荐阅读