What is happening is that being a promise, you can not show the log before it ends.
How it works
When making a request to read or write to the database with a promise, it behaves similar to a valueEventListener
that we use with Firebase, this type of requests are asynchronous, this means that while your promise is executed , the next block will be executed.
Then what you have to do is the following, you execute the promise, which has 3 states
- Pending
- Fullfilled
- Rejected (Could not perform, here we must use a catch or
return another value)
After you execute the promise, you have to wait until the value you are looking for is returned to show it with the console.log
, otherwise the console log will be executed before the promise ends and you are always going to have null
As I see in your code, you are running the console.log out of the promise without first waiting for the data to be brought.
So you should fix it by putting that console.log inside the function that you execute on your promise
function fun(dato) {
console.log(dato);
dat = dato;
console.log(dat);
}
In this way, the function fun(dato)
will contain the value of dat to be assigned to console.log
otherwise you can never access it if you do not have it.
Remember that each promise must return a catch or return, since you need to manage all 3 states of the same, so your promise should remain that way. Remember to use exists()
to ask before sending the data to your function if it exists in that reference, otherwise you will always end up with another null
var dat = {};
firebaseService.database().ref('Users/' + us.uid).once('value').then(function(snapshot) {
if (snapshot.exists()) {
let dato = snapshot.val().countShops
fun(dato);
}
}).catch(err => {
console.log(err);
console.log("Ocurrio un error al traer los datos");
});
function fun(dato) {
console.log(dato);
dat = dato;
console.log(dat);
}