Firebase - Variables out of scope

廉价感情. 提交于 2019-12-12 03:23:16

问题


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

回答1:


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

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. Do all of your logic in the .on() function.
  2. Use an observable or another framework like Angular+AngularFire that simplifies async data.


来源:https://stackoverflow.com/questions/33807528/firebase-variables-out-of-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!