如何使用Firebase在javascript中使局部变量成为全局变量? [英] How to make a local variable a global variable in javascript with firebase?

查看:65
本文介绍了如何使用Firebase在javascript中使局部变量成为全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过firebase api提取一个值并将其设为全局变量,以便可以在代码中的其他位置引用它

I'd like pull a value via firebase api and make it a global variable, so that I can refer to it else where in the code

我希望下面的代码在从firebase中提取值并可以在函数外部使用它的情况下工作(

I'd like for the below code to work where I pull a value from firebase and can use it outside of the function (http://jsfiddle.net/chrisguzman/jb4qLxtb/)

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});

alert(Variable);

我尝试用下面的var定义它,但是没有运气( http://jsfiddle.net/chrisguzman/jb4qLxtb/1/)

I've tried defining it with var below with no luck (http://jsfiddle.net/chrisguzman/jb4qLxtb/1/)

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

var MyVariable = ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});


alert(MyVariable);

我也尝试将其定义为一个没有运气的函数: http://jsfiddle.净/chrisguzman/jb4qLxtb/2/

I've also tried to define it as a function with no luck: http://jsfiddle.net/chrisguzman/jb4qLxtb/2/

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

function myFunction() { ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    return Variable;
});};


alert(myFunction());

推荐答案

对于异步编程,您只能在回调内部或从那里调用的函数中使用响应,并将数据传递给该响应.您不能将其填充到全局变量中,以尝试解决响应是异步的这一事实.您也不能从异步回调中返回值,并且不能期望从主机函数中返回该值.主机函数已经执行完毕,回调在一段时间后被调用.

With asynchronous programming, you can only use the response inside the callback or in a function you call from there and pass the data to. You can't stuff it into a global variable to try to work around the fact that the response is asynchronous. You also can't return a value form an asynchronous callback and expect that value to be returned from the host function. The host function has already finished executing and the callback is called some time later.

这是一种可行的方法:

var ref = new Firebase('https://helloworldtest.firebaseIO.com/');

ref.on('value', function (snapshot) {
    var Variable = snapshot.child("text").val();
    alert(Variable);
});

要了解更多有关处理异步响应的选项的信息,可以阅读以下有关ajax调用的答案,但是概念是相同的:

To read a lot more about your options for handling an async response, you can read this answer which is about an ajax call, but the concept is the same: How do I return the response from an asynchronous call?.

这篇关于如何使用Firebase在javascript中使局部变量成为全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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