如何将Firestore查询转换为Javascript数组 [英] How to turn Firestore query into a Javascript array

查看:91
本文介绍了如何将Firestore查询转换为Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试导出执行查询的firestore函数,并返回包含该查询中对象的数组.我正在尝试从文档的子集合中获取数据,并获取返回以呈现给客户端的文档对象数组.

I am trying to export a firestore function that performs a query and returns an array containing the objects in that query. I am trying to get data from a subcollection of a document, and get an array of document objects returned to render to the client.

我已经尝试了以下方法,但无法正常工作(例如,对象返回空白).我认为这与对诺言的处理不当有关,但我自己无法解决.感谢您的帮助.

I've tried the below but it's not working (e.g. the object returns blank). I think this has to do with improper handling of promises, but couldn't figure it out on my own. Thanks for your help.

export const getEvents = (id) => {
  let events = [];
  firestore.collection('users')
    .doc(id)
    .collection('events')
    .get()
    .then((snapshot) => {
      snapshot.forEach((doc) => events.push(doc));
    });
    return events;
 };

推荐答案

您正确地确定了此问题与对诺言的处理有关.您要返回事件数组,然后才能填充它,因为promise尚未解决.

You are correct in identifying this problem is related to the handling of promises. You are returning the events array before it has a chance to be populated, because the promise hasn't resolved yet.

如果您的环境允许,我建议您使用async/await,因为这样会使代码更易于阅读和理解,例如:

If your environment allows it, I would recommend that you use async/await, because it makes the code much easier to read and understand, like this:

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

但是,如果您不能使用异步/等待,则可以使用promises.但是您只需要在获取数据后解决承诺:

But if you can't use async/await you can do it with promises. But you need to only resolve the promise after the data is fetched:

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

这篇关于如何将Firestore查询转换为Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆