简单的Firebase数据检索 [英] Simple Firebase Data retrieval

查看:122
本文介绍了简单的Firebase数据检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图执行一个简单的火力点数据检索。以下是我的

  var fb = new Firebase(https://< my-app> .firebaseio.com ); 
$ b fb.on('value',function(snapshot){
var db = snapshot.val();
var speed = db ['speed'];
});

console.log(speed);

rnd = Math.floor(Math.random()* 7);
fb.set({speed:rnd});

我遇到的问题是速度被卡在fb.on区域内。我怎样才能把它解决呢?

解决方案

您的代码没有被卡住,而是错误地调用它。 / b>

  fb.on('value',function(snapshot){
var db = snapshot.val();
var speed = db ['speed'];
});

这里提供了一个局部变量 speed 。这个变量可能会被设置正确,但你没有做任何事情。

  console.log(speed); 

rnd = Math.floor(Math.random()* 7);
fb.set({speed:rnd});

设置事件处理程序( fb .on('value',...)),但代码异步运行。这个函数不仅在这个时候可能没有运行,而且在这里你正在访问一个未声明的变量 speed ,并且因为没有声明它是一个自动的全局变量 window.speed ,而不是回调函数中的本地变量 speed



将回调函数中的 console.log 移到正确的时间执行。另外,总是声明你的变量。


I'm just trying to perform a simple firebase data retrieval. Here's what I have

var fb = new Firebase("https://<my-app>.firebaseio.com");

fb.on('value', function(snapshot) {
  var db = snapshot.val();
  var speed = db['speed'];
 });

console.log(speed);

rnd = Math.floor( Math.random() * 7 );
fb.set({ speed: rnd});

The problem I have is speed is stuck inside of the fb.on area. How do I get it out of there?

解决方案

Your code isn't getting stuck, you're calling it incorrectly.

fb.on('value', function(snapshot) {
  var db = snapshot.val();
  var speed = db['speed'];
});

Here you're providing a callback function with a local variable speed. This variable will probably be set correctly, but you're not doing anything with it.

console.log(speed);

rnd = Math.floor( Math.random() * 7 );
fb.set({ speed: rnd});

This code runs straight after you've set up the event handler (fb.on( 'value', ... )) but that code runs asynchronously. Not only will that function probably not have ran at this point, but here you are accessing an undeclared variable speed, and because it isn't declared it is an automatic global variable window.speed, and not the local variable speed in the callback function.

Move the console.log inside of the callback function to execute it at the right time. Also, always declare your variables.

这篇关于简单的Firebase数据检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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