javascript - 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:
How to Access the segments Array in the Path in the qf in PromiseResult. I tried some object restructuring but it did not work.
解决方案
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'));
});
});
推荐阅读
- python - InvalidArgumentError,我应该怎么做才能解决这个错误?
- python - Scrapy CloseSpider 异常是否仍然重定向到用户定义的管道关闭过程?
- javascript - 无法从视图获取值到模型
- javascript - DOMException:“无法创建没有本地轨道、没有 offerToReceiveAudio/Video 和没有 DataChannel 的报价”webRTC 应用
- latex - 如何在 Rmarkdown 文档中创建乳胶表?
- php - 如何使用 PHP、MySQL 和 mysqli_query 在 db 中上传和保存文件?
- c# - 如何全局挂钩触摸事件并知道触摸的XY位置?
- jenkins - 使用 Jenkins 部署时如何检查 jar 是否成功启动?
- clang++ - 如何散列 Clang AST 节点以用作 C++ 无序映射中的键?
- html - 如何删除引导导航栏上的填充