Firebase:child_add完成时如何获取数据 [英] Firebase: how to get the data when child_added complete

查看:90
本文介绍了Firebase:child_add完成时如何获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我需要获取所有 event 对象.每个 event 对象都有一个 city_id 属性,该属性是指向具有所有 city 列表中的单个 city 对象的关系键.>.

I have a case when I need to fetch all event objects. Each event object has a property city_id which is a relationship key to a single city object from the list with all cities.

...
|- events
|  |- event_id
|  |   |- title
|  |   |- city_id
|
|- cities
|  |- city_id
|  |   |- name
|  |   |- location
...

所以我做了类似 join 查询的事情:

So I a doing something like a join query:

const rootRef = firebase.database().ref();

async function getAllEvents() {
    const eventsRef = rootRef.child('events');
    const eventsArray = [];

    await eventsRef.on('child_added', async (snapshot) => {
        const eventObject = snapshot.val();
        const cityObject = await getEventCity(eventObject.city_id);
        eventObject.city = cityObject;
        eventsArray.psuh(eventObject);
    });

    return eventsArray;
}

function getEventCity(cityId) {
    return rootRef.child('cities')
        .child(cityId)
        .once('value', (venue) => {
            return venue.val();
        });
}

一切都与查询配合良好.问题是我想将所有事件都放在一个数组中,但是以下代码不起作用:

Everything works well with the queries. The problem is that I want to get all events in an array, but the following code doesn't work:

const allEvents = getAllEvents();

eventsRef.on('child_added)之前,我已经 await 的事件仍会返回初始的空数组.

Event that I have await before eventsRef.on('child_added) it still returns the initial empty array.

我做错了什么,如何在 .on('child_added')上完成所有内容的获取时捕捉到这一刻?

What I am doing wrong and how can I catch this moment when the fetching of all on .on('child_added') is done?

推荐答案

知道何时完成初始数据加载的唯一方法是使用 value 事件.我还没有真正使用过 async / await ,但是希望您需要这样的东西:

The only way to know when loading of the initial data is done is to use a value event. I haven't really used async/await yet, but expect you'll need something like this:

async function getAllEvents() {
    const eventsRef = rootRef.child('events');
    const eventsArray = [];

    await eventsRef.on('value', async (snapshot) => {
      snapshot.foreach(function(child) {
        const eventObject = child.val();
        const cityObject = await getEventCity(eventObject.city_id);
        eventObject.city = cityObject;
        eventsArray.push(eventObject);
      });
    });

    return eventsArray;
}

这篇关于Firebase:child_add完成时如何获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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