JavaScript - Firebase 值到全局变量 [英] JavaScript - Firebase value to global variable

查看:24
本文介绍了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:

在开始加载值之前

开始加载值后

加载值

这可能不是您期望的顺序.但它完美地解释了为什么在访问全局变量时未设置它:该值尚未从数据库中返回.

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() 返回一个 promise 的事实,这样可以更轻松地处理结果:

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:

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

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