Javascript 如何从Firestore promise返回数据?

Javascript 如何从Firestore promise返回数据?,javascript,firebase,google-cloud-firestore,promise,Javascript,Firebase,Google Cloud Firestore,Promise,我有这个代码,它返回某个文档的父级。 console.log(doc.ref.parent.get()) 我使用collectionGroup搜索是否存在与登录到应用程序的用户的电子邮件相同的电子邮件用户 var nameRef = db .collectionGroup('Users') .where('email', '==', currentUser.email) useEffect(() => { nameRef.get().then((snapsho

我有这个代码,它返回某个文档的父级。
console.log(doc.ref.parent.get())
我使用collectionGroup搜索是否存在与登录到应用程序的用户的电子邮件相同的电子邮件用户

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

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


如何在PromiserResult中访问qf路径中的segments数组。我尝试了一些对象重组,但没有成功。

您的代码中有几个问题:

#1/在
useffect
函数中不返回任何内容

#2/
doc.ref.parent.get()
是异步的,将立即返回并承诺。问题在于
forEach()
循环不会等待这些承诺实现。请参阅更多解释。一个经典的解决方案是使用如下所示

#3/最后但并非最不重要的一点是,请注意,
useffect
函数是异步的

因此,以下几点可以做到:

  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')); 
    });
  }); 
  

这回答了你的问题吗?请分享整个相关的代码片段。什么
doc
ref
parent
已经存在?我用相关代码更新了帖子。谢谢更新。为什么要访问
segments
属性?因为在segments上,用户所属的主集合中有所有集合和文档。简单地说,我想得到的文件,属于登录用户。谢谢你的帮助。我尝试了您编写的代码,但无法读取未定义错误的属性“then”。似乎.then函数不返回任何内容。我已经用对象分解解决了这个错误。感谢您抽出时间:)。