将Firebase数据存储到JavaScript中的数组中 [英] Store Firebase data into array in JavaScript

查看:83
本文介绍了将Firebase数据存储到JavaScript中的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Firebase获取数据并将其存储到数组中. 但是,当我尝试从数组中获取数据时,它变得不确定. 谁能告诉我为什么会发生吗?

I tried to get the data from Firebase and store it into an array. However, when I try to get the data from the array, it became undefined. Can anyone tell me why would it happened?

var events = [];
var databaseRef = database.ref("events").orderByChild("date");

databaseRef.on('child_added', function(snapshot) {
  var event = snapshot.val(); 

  events.push({
    title: event.title, 
    content: event.content
  });
});

console.log(events);
console.log(events[0]);
console.log(events.pop());

在#1中,所有数据都作为对象存储在数组中. 但是在#2& 3中,它返回undefined

In #1, all the data is stored as object in the array. But in #2&3, it returns undefined

添加:#1返回:

[]
    0 : Object
        content : "Rehoncus. Aliquam nibh antegestas id dictum a, commodo. Praesenterto faucibus malesuada faucibu"
        title : "Tivamus at magna non nunc"
    1 : Object
        content : "Rehoncus. Aliquam nibh antegestas id dictum a, commodo. Praesenterto faucibus malesuada faucibu"
        title : "Vivamus at magna non nunc"

推荐答案

您的数据是从Firebase异步加载的.在您的console.log语句执行时,数据尚未从Firebase服务器返回.通过添加一些额外的日志语句,最容易看到这一点:

Your data is loaded from Firebase asynchronously. By the time your console.log statements execute, the data hasn't come back from the Firebase servers yet. This is easiest to see by adding a few extra log statements:

var events = [];
var databaseRef = database.ref("events").orderByChild("date");

console.log("before attaching listener");
databaseRef.on('child_added', function(snapshot) {
  console.log("in listener callback");
});
console.log("after attaching listener");

日志语句的顺序为:

在附加侦听器之前

before attaching listener

附加监听器后

在侦听器回调中

在侦听器回调中

在侦听器回调中

这可能不是您所期望的.但是,针对基于云的服务(例如Firebase数据库)进行编程时,这非常常见.实际上:使用Firebase数据库,这是处理数据连续同步的唯一方法.如果明天有人添加新活动,您将获得另一个活动:

This is probably not what you expected. But it is very common when programming against cloud-based services, such as the Firebase Database. In fact: with Firebase Database this is the only way to handle continuous synchronization of data. If somebody adds a new event tomorrow, you will get another:

在侦听器回调中

in listener callback

要处理这种异步负载,通常必须反转思维方式.因此,处理代码的通常方法是:首先加载数据,然后对数据进行处理.使用Firebase,您需要做出反应:无论何时获得数据,我都会对其进行处理.

To deal with this asynchronous loading, you typically have to invert your way of thinking. The usual way that we deal with code is sequently: first I will load the data, then I will do something with that data. With Firebase, you need to think reactively: whenever I get data, I will do something with it.

假设您要为每个事件 向HTML添加元素,并更新平均事件持续时间.您可以通过以下方式做到这一点:

Say you want to add an element to the HTML for each event and update an average event duration. You can do this by:

var events = [];
var databaseRef = database.ref("events").orderByChild("date");

databaseRef.on('child_added', function(snapshot) {
  var event = snapshot.val(); 

  // add the event to the UI
  var elm = document.createElement('li');
  elm.id = 'event-'+snapshot.key;
  elm.innerText = event.title;
  document.querySelector('#event-list').appendChild(elm);

  // add the event to our list
  events.push({
    title: event.title, 
    content: event.content
  });

  // update/recalculate our avg event duration
  calculateAverageEventDuration(events);
});

这篇关于将Firebase数据存储到JavaScript中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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