Variable scope issue when accessing Firebase from Node.js [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
My current code for accessing my Firebase databse from Node.js looks roughly like this.:
var DesiredValue = "#";
ref.child("Example").once("value", function(snapshot) {
DesiredValue = snapshot.val();
console.log(DesiredValue)
});
console.log(DesiredValue)
It returns
>42
>#
where 42 is the value I want to grab, but I can't figure out how to retrieve it outside the scope of ref.child.(). I have tried the following which doesn't work.
var DesiredValue = ref.child("Example").once("value", function(snapshot) {
var DesiredValue = snapshot.val();
console.log(DesiredValue)
return DesiredValue
});
console.log(DesiredValue)
All I want to do is use 42 in the remainder of the code. Based on what I have read there might be some way of using JavaScript's 'this' to achieve my goal, but I am worried of messing with global variables and think there must be an easier way?

It's a callback you may use a promise, when it is resolved then you can use the value out of function or handle the value inside the callback, otherwise the code it's executed without waiting

Related

why can't my variable display result value if its outside the function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 months ago.
I'm trying to retrieve data from database and store the value into a variable, but it gives me undefined value which means variable is not storing the data.
var n1;
var reff=firebase.database().ref('login-demi/');
reff.on("child_added", function(data){
var newnum=data.val();
n1=newnum.number; //4
if (n1==4){
n1=newnum.age;
}
});
console.log(n1);
But if I try to "put console.log(n1)" inside the function under "n1=newnum.age;" then it will display the value, but i want the variable to store the value and display it outside the function can I know how can I do that?
I think the problem is that the function "reff.on" is an event function and what happens is that you print the n1 variable before the function is executed.
Therefore, you will only be able to access this data from within the function, Or you will build a specific function to verify that the previous function has been executed before you print the n1.
Notice how they only access the information from within the function in the Firebase documentation : https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#parameters

returning a value from async/await promise [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to find a simple example of how to return a value from async/await where the value is easily accessed outside the async function.
Would the following two examples be considered the optimum way to return a value from an async/await function?
In other words, if the value returned from an async/await needs to be saved and used in other parts of the code, what would be the best way to save the value?
this is the easiest example i could find:
async function f() {
return 1;
}
var returnedValue = null; // variable to hold promise result
f().then( (result) => returnedValue = result );
console.log(returnedValue); // 1
or perhaps would it be better to use an object?
async function f(varInput) {
varInput.value = 1;
}
myObject = {} ; myObject.value=null;
f(myObject);
console.log(myObject.value); // 1
thank you.
My answer addresses two subjects here:
1) Async function returns a promise that resolves to a value. So, for instance your first function can be used as per your example. It can also be used like this:
async function() {
const x = await f();
}
2) Immutability - the second solution will work but it makes your funciton "impure". It is not bad in itself, but beware of side effects this might cause (for instance, if you change an app-wide singleton value without other components being notified about it, some part of your app might go out of sync with the data).
Hope this answers your question.

How to handle returning an inner callback variable? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
How do I access a variable inside a callback without reassigning it to a variable first?
For example, the following code works:
let volume = 0;
loudness.getVolume((err, vol) => {
volume = vol;
});
But what if I wanted it to be assignable directly to a const. The following returns undefined:
const volume = loudness.getVolume((err, vol) => vol));
The short answer is you can not. The callback function exists in it's own scope isolated from the rest of the code. The only way to extract that info to be used in the rest of the code is to assign it to a variable that exists in a parent scope.
In simple terms do what you did in your first example.

Cannot assign value to variable by reference in Javascript [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I would like to assign value to the variable IMLoginReq inside a ProtoBuf load function, but its not working, can anyone help?
var IMLoginReq;
protobuf.load("./pb/IM.Login.proto", (err, root) => {
// Obtain a message type
IMLoginReq = root.lookup("IM.Login.IMLoginReq");
console.log(IMLoginReq);//<== is not undefined
});
console.log(IMLoginReq);//<== is undefined
The load() method is asynchronous. As such the console.log at the end will happen before the load finishes. Instead of trying to treat this as procedural logic, which it is not, you should instead use the IMLoginReq inside the success method that you have.
Thats because you are trying to call it before its loaded. You should have a callback function like success so it will be there.
You can also use promises by omitting the callback:
protobuf.load("awesome.proto")
.then(function(root) {
...
});

variable no accessible after a Firebase call [duplicate]

This question already has answers here:
Passing variable in parent scope to callback function
(3 answers)
Closed 8 years ago.
I'm using Firebase to access to same data, but i can't use the data out of the function used to access it.
How i can make a console log of the data just accessed instead of the initial value?
var whatNeed = 'hello';
gameData = new Firebase('https://thegame.firebaseio.com/gameData');
gameData.on("value", function(snapshot) {
var data = snapshot.val();
whatNeed = data.property;
});
console.log(whatNeed);
whatNeed will always contain the initial value when called outside of your callback as the console.log will be called first since the value event handler is asynchronous.

Categories