【问题标题】:Firebase: how to get the data when child_added completeFirebase:child_added 完成时如何获取数据
【发布时间】:2017-11-03 05:53:40
【问题描述】:

我有一个案例需要获取所有 event 对象。每个event 对象都有一个属性city_id,它是列表中单个city 对象的关系键,所有cities

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

所以我做了类似join 查询:

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

一切都适用于查询。问题是我想获取数组中的所有事件,但是下面的代码不起作用:

const allEvents = getAllEvents();

我在eventsRef.on('child_added) 之前有await 的事件仍然返回初始的空数组。

我做错了什么,当.on('child_added') 上的所有内容的获取完成时,我如何才能抓住这一时刻?

【问题讨论】:

    标签: javascript firebase asynchronous firebase-realtime-database async-await


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的解决方案。我对async/await 有很多问题,所以我使用了Promise.all,在那里我推送每个getEventCity(eventObject.city_id) 请求;)
    • 我认为 eventsRef.once 是更好的解决方案(它支持 then 的承诺)。
    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    相关资源
    最近更新 更多