JavaScript-Firebase值转换为全局变量 [英] JavaScript - Firebase value to global variable

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

问题描述

ref.child("path").on("value", snapshot => {
  var z = Object.keys(snapshot.val())[2];
  y = snapshot.val()[z];

  //Call the friggin thing
  exportData(y);

  function exportData(y) {
    exporting(y);
  }
});

function exporting(y) {
  var x = y;
  //console.log(y);
  return x;
}

我想将x存储在全局变量中.

I want to store x in a global variable.

我不能在下面做代码,因为不会传递'y'. "y"是局部变量.

I cannot do code just below because 'y' will not be passed through. 'y' is a local variable.

var answer = exporting();
answer();

推荐答案

将值存储在全局变量中不是问题,这是何时弄乱了你.

Storing the value in a global variable is not a problem, it's the when that is messing you up.

数据是从Firebase异步加载的.这意味着代码不会按照您预期的顺序运行.您可以通过在其中添加一些日志记录来最轻松地看到这一点:

Data is loaded from Firebase asynchronously. This means that code doesn't run in the order that you probably expected. You can most easily see this by putting some logging in there:

console.log("Before starting to load value");
ref.child("path").on("value", snapshot => {
  console.log("Loaded value");
});
console.log("After starting to load value");

运行此代码时,它会打印:

When you run this code it prints:

开始加载值之前

Before starting to load value

开始加载值后

已加载值

这可能不是您期望的顺序.但这很好地说明了为什么在访问全局变量时未设置全局变量:该值尚未从数据库返回.

That is probably not the order you expected. But it explains perfectly why the global variable is not set when you access it: the value hasn't come back from the database yet.

这就是为什么要在回调函数内部内部中移动需要数据库中数据的代码的原因.或者,您可以使用once()返回承诺的事实,这样可以更轻松地处理结果:

That's why you'll want to move the code that needs the data from the database inside the callback function. Alternatively you can use the fact that once() returns a promise, which makes it easier to deal with as a result:

function loadData() {
 return ref.child("path").once("value");
});

loadData().then((snapshot) => {
  ... use the data from snapshot
});

请注意,对于新手来说,异步加载是令人难以置信的常见混淆源.我强烈建议您查看有关该主题的其他一些问题:

Note that is asynchronous loading is an incredibly common source of confusion for developers who are new to it. I highly recommend checking out some of the other questions on the topic:

  • How to return value from an asynchronous callback function?
  • How do I return the response from an asynchronous call?
  • How to get returned a value by a callback function
  • Return a value from a Firebase JS callback method (DAL) to another function (controller)
  • Firebase return output from function

这篇关于JavaScript-Firebase值转换为全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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