How to turn Firestore query into a Javascript array

Deadly 提交于 2021-02-08 05:16:30

问题


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

回答1:


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.

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

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


来源:https://stackoverflow.com/questions/52530006/how-to-turn-firestore-query-into-a-javascript-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!