gpt4 book ai didi

javascript - 找到 CollectionGroup 时获取 fullData

转载 作者:行者123 更新时间:2023-12-03 16:57:38 25 4
gpt4 key购买 nike

我在查询 1 个集合中的所有数据时遇到问题
User-> UidUser-> InfoUser (POST (Collection), name, age ...)
然后,我使用下面的代码来获取 collectionsGroup(帖子),但是如何获取用户的姓名和年龄?
当我使用 2 个嵌套循环时,另一个问题是 forEach 不能在其中使用 Await 和 Async 使我丢失数据。

  getData = async () => {

await firebase.firestore().collection('user').doc(Fire.shared.uid).onSnapshot(documentSnapshot => {

firebase.firestore().collectionGroup('Post').where('uid', 'in',
documentSnapshot.data().Followings).get().then(querySnapshot => {

const Post = [];
querySnapshot.forEach(post => {


Post.push({ data: post.data() }) // This is correct and get full data's Post


});
this.setState({ dataPost: Post })
})
})
}

await firebase.firestore().collection('user').doc(Fire.shared.uid).onSnapshot(documentSnapshot => {

firebase.firestore().collectionGroup('Post').where('uid', 'in', documentSnapshot.data().Followings).get().then(querySnapshot => {

const Post = [];

querySnapshot.forEach(async (post) => {
// Incorrect because forEach don't wait callback => Lose a documents's user //

await firebase.firestore().collection('user').doc(post.data().id).onSnapshot(user => {

Post.push({ data: post.data(),user: documentSnapshot.data() })

})
});
this.setState({ dataPost: Post })
})
})

最佳答案

我认为 promise.all 解决了这个问题

firebase.firestore()
.collection("user")
.doc(Fire.shared.uid)
.onSnapshot((documentSnapshot) => {
firebase
.firestore()
.collectionGroup("Post")
.where("uid", "in", documentSnapshot.data().Followings)
.get()
.then((querySnapshot) => {
const Post = [];

querySnapshot.forEach((post) => {
Post.push(new Promise((resolve, reject) => {
firebase
.firestore()
.collection("user")
.doc(post.data().id)
.onSnapshot((user) => {
resolve({ data: post.data(), user: documentSnapshot.data() });
});
}))

});
Promise.all(Post).then(res => {
console.log(res)
this.setState({ dataPost: res})

})
});
});
我使用 setTimeout 函数和 forEach 函数的简单示例展示了它是如何工作的

async function call() {
const nums = [1, 2, 3, 4, 5];
const promises = [];
nums.forEach((res) => {
setTimeout(() => {
promises.push(res*2);
}, 10000);
});
console.log(promises);
}
call();



async function call() {
const nums = [1, 2, 3, 4, 5];
const promises = [];
nums.forEach((res) => {
setTimeout(() => {
promises.push(res*2);
}, 10000);
});

Promise.all(promises).then((res) => {
console.log("res", res);
});
}
call();

在上面的例子中,输出是一个空数组,所以我想办法解决这个问题

   
async function call() {
const nums = [1, 2, 3, 4, 5];
const promises = [];
nums.forEach((res) => {
promises.push(
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(res * 2);
}, 3000);
})
);
});

Promise.all(promises).then((res) => {
console.log("res", res);
});
}
call();

关于javascript - 找到 CollectionGroup 时获取 fullData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66665975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com