Firebase-使用回调在数组中检索和存储数据 [英] Firebase - Retrieving and storing data in array with callbacks

查看:90
本文介绍了Firebase-使用回调在数组中检索和存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Firebase回调从我的实时数据库中检索数据,将其存储在数组中,然后将该数据用于数据可视化。但是,当我登录阵列的控制台时,它返回空。我引用了



最终,我希望能够使用数组通过Chart.js库生成图表:

  //条形图显示按性别划分的学生总数。 
var ctx = document.getElementById( myChart4)。getContext('2d');
var myChart =新图表(ctx,{
类型: bar,
数据:{
标签:[男性,女性,非二进制 ,其他,未指定],
数据集:[{{
数据:genderData,
backgroundColor:[
'rgba(255,99,132,0.2)',
'rgba(54,162,235,0.2)',
'rgba(255,206,86,0.2)',
'rgba(75,192,192,0.2)' ,
'rgba(153、102、255、0.2)',
'rgba(255、159、64、0.2)',
],
borderColor:[
'rgba(255,99,132,1)',
'rgba(54,162,235,1)',
'rgba(255,206,86,1)',
'rgba(75,192,192,1)',
'rgba(153,102,255,1)',
'rgba(255,159,64,1)'
],
borderWidth:1
}]
},
选项:{
标题:{
显示:true,
文字:按性别划分的学生总数
},
图例:{
显示:false
},
比例尺:{
yAxes:[{{
滴答:{
beginAtZero:true
}
}]
}
}
});

我一直在解决这个问题达数小时之久,没有解决方案。我只想用我的数据库数据创建一个简单的数组,但是我遇到了很多麻烦。我真的希望有人能帮我找到一个优雅的解决方案。



编辑



以防万一:




解决方案

Firebase异步加载数据。这意味着任何需要访问数据的代码都必须在 then()回调内部,或者必须使用 then()

使用当前定义的 getData ,您可以调用它并通过以下方式使用数据:

  getData()。then((data)=> {
console.log( In callback);
console.log(data);
console.log(genderData);
})
console.log(外部回调);
console.log(genderData);

如果运行此代码,您将看到:


外部回调


[]


内部回调


[item1,item2,.. 。]


[item1,item2,...]


此处要注意的事项:


  1. 外部回调代码运行之前 内部回调代码,这可能不是您期望的。

  2. 回调之外的代码运行,数组仍然为空。仅在回调内部的代码运行后,数组中才会包含数据。

  3. 在回调内部, genderData data 是相同的。这是因为您在回调中返回性别数据,然后将其冒泡到 then()方法。

为您提供的最终解决方案是,创建图表(即您需要数据的位置)的代码应在内部 然后回调之一,以便在数据加载后立即被调用。例如:

  getData()。then((data)=> {
var myChart = new Chart(ctx,{
类型: bar,
数据:{
标签:[男性,女性,非二进制,其他,未指定] ,
数据集:[{
数据:数据,
...


I'm want to use Firebase callbacks to retrieve data from my realtime database, store it in an array, then use that data for data visualization purposes. But when I log the console for the array, it returns empty. I referenced this post in an attempt to understand/fix my error, but I'm still having a lot of trouble.

var genderData=[];
// Get counter values.
function getData(){
    var ref = firebase.database().ref().child('counters');

    return ref.once('value').then((snapshot) => {
        snapshot.forEach((element) => {
            genderData.push(element.val()['Male']);
        });
        return genderData;
    });
}

console.log(genderData);

My console shows:

Eventually, I want to be able to use my array to produce a chart with the Chart.js library:

// Bar graph displaying the total number of students by gender.
var ctx = document.getElementById("myChart4").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
        datasets: [{
            data: genderData,
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)',
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        title: {
            display: true,
            text: 'Total Students by Gender'
        },
        legend:{
            display: false
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});

I've been working on this problem for hours, with no solution. All I want is to create a simple array with my database data, but I've had so much trouble. I really hope someone can help me find an elegant solution.

EDIT:

A bit of my database structure, just in case:

解决方案

Firebase loads data asynchronously. This means that any code that needs access to the data, must be inside the then() callback, or must use a then() callback of its own.

With your current definition of getData, you can call it and use the data with:

getData().then((data) => {
  console.log("In callback");
  console.log(data);
  console.log(genderData);
})
console.log("Outside callback");
console.log(genderData);

If you run this code, you'll see:

Outside callback

[]

Inside callback

[ item1, item2, ... ]

[ item1, item2, ... ]

The things to note here:

  1. the Outside callback code runs before the Inside callback code, which is probably not what you expected.
  2. the code outside of the callback runs, the array is still empty. Only once the code inside the callback has run, does the array contain data.
  3. inside the callback, the genderData and the data are the same. This is because you return genderData in the callback, which is then bubbled up to the then() method.

The final solution for you is that the code that creates the chart (which is where you need the data), should be inside one of the then callbacks so that it gets called once the data has loaded. For example:

getData().then((data) => {
   var myChart = new Chart(ctx, {
     type: 'bar',
     data: {
        labels: ["Male", "Female", "Non-Binary", "Other", "Unspecified"],
        datasets: [{
            data: data,
            ... 

这篇关于Firebase-使用回调在数组中检索和存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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