【问题标题】:How to turn Firestore query into a Javascript array如何将 Firestore 查询转换为 Javascript 数组
【发布时间】:2019-03-02 22:57:18
【问题描述】:

我正在尝试导出一个执行查询并返回包含该查询中的对象的数组的 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;
 };

【问题讨论】:

    标签: arrays firebase google-cloud-firestore es6-promise


    【解决方案1】:

    您正确地确定了此问题与对承诺的处理有关。您将在有机会填充之前返回 events 数组,因为 promise 尚未解决。

    如果您的环境允许,我建议您使用 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 来实现。但是您只需要在获取数据后解决 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);
                });
        });
    };
    

    【讨论】:

    • 谢谢 - 如果我遇到任何问题,我会试试这个并跟进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多