Firebase-变量超出范围 [英] Firebase - Variables out of scope

查看:60
本文介绍了Firebase-变量超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这是一个业余问题,请原谅我,我是第一次接触API.我一直在与Firebase合作,以存储在整个脚本中使用的得分"列表数组.在Firebase函数之一中,值会更新,但不会在全局范围内更新值.我不确定目前缺少什么.这是一个代码段,值0和1记录在控制台上.

Forgive me if this is an amateur question, I'm new to using APIs. I've been working with Firebase to store a "scores" list array which is used throughout my script. Within one of the Firebase functions, the value is updated, but the value isn't updated within the global scope. I'm not sure what I'm missing at this point. Here's a code snippet, the values of 0 and 1 are logged on console.

window.global_counter = 0;
window.score = 0;
window.listScores = {"GMS":0, "Vacc":0, "CH":0, "GSF":0, "Pharm":0, "GF":0, "Pharma":0, "Sti":0};

var ref = new Firebase("https://xxx-xxx-xxx-xxx.firebaseio.com/");

// show chart data 
ref.on("value", function(snapshot){
    listScores["GMS"] = snapshot.child("GMS").numChildren();
    console.log("listScores['GMS'] inside: " + listScores["GMS"]);
    // 1
    listScores["Vacc"] = snapshot.child("Vacc").numChildren();
    listScores["CH"] = snapshot.child("CH").numChildren();
    listScores["GSF"] = snapshot.child("GSF").numChildren();
    listScores["Pharm"] = snapshot.child("Pharm").numChildren();
    listScores["GF"] = snapshot.child("GF").numChildren();
    listScores["Pharma"] = snapshot.child("Pharma").numChildren();
    listScores["Sti"] = snapshot.child("Sti").numChildren();
});

console.log("listScores['GMS'] outside: " + listScores["GMS"]);
// 0

推荐答案

这并不是说的范围问题.Firebase异步返回数据.

It's not a scope issue per-say. Firebase returns data asynchronously.

Firebase通过网络下载数据.它异步执行此操作,因此它不会阻止UI活动.最终将下载,但不会在您将其登录到脚本中时下载.

Firebase downloads the data over the network. It does this asynchronously, so it doesn't block UI activity. The will eventually download, but not by the time you log it in your script.

您可以使用一些选项处理异步数据.

You have a few options to work with async data.

  1. .on()函数中执行所有逻辑.
  2. 使用类似于 Angular + AngularFire 的可观察框架或其他框架数据.
  1. Do all of your logic in the .on() function.
  2. Use an observable or another framework like Angular+AngularFire that simplifies async data.

这篇关于Firebase-变量超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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