我正在尝试导出一个 firestore 函数,该函数执行查询并返回包含该查询中的对象的数组。我正在尝试从文档的子集合中获取数据,并获取返回的文档对象数组以呈现给客户端。
我已经尝试了以下方法,但它不起作用(例如,对象返回空白)。我认为这与承诺处理不当有关,但我自己无法解决。感谢您的帮助。
export const getEvents = (id) => {
let events = [];
firestore.collection('users')
.doc(id)
.collection('events')
.get()
.then((snapshot) => {
snapshot.forEach((doc) => events.push(doc));
});
return events;
};
您正确地确定此问题与承诺的处理有关。您将在有机会填充事件数组之前返回事件数组,因为承诺尚未解决。
如果您的环境允许,我建议您使用 async/await,因为它使代码更容易阅读和理解,如下所示:
export const getEvents = async (id) => {
let events = [];
const snapshot = await firestore.collection('users')
.doc(id)
.collection('events')
.get()
snapshot.forEach((doc) => events.push(doc));
return events;
};
但如果你不能使用 async/await,你可以使用 Promise 来实现。但您只需要在获取数据后解决承诺:
const getEvents = (id) => {
return new Promise((resolve, reject) => {
let events = [];
const snapshot = firestore.collection('users')
.doc(id)
.collection('events')
.get()
.then((snapshot) => {
snapshot.forEach((doc) => events.push(doc));
resolve(events); // return the events only after they are fetched
})
.catch(error => {
reject(error);
});
});
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)