promises in firebase

0

I'm working with real time firebase, and I have a problem getting a value within a promise, because I would like that value to be stored in a global variable

   firebaseService.database().ref('Users/' + us.uid).once('value').then(function(snapshot) {
    let dato = snapshot.val().countShops
    fun(dato);
     })

var dat = {};

function fun(dato) {
    console.log(dato);
    dat = dato;
}
console.log(dat);

when doing the last console, it does not show me the info, because the object appears empty, but if we look at the console log inside the fun function it shows me the value correctly. I have been reading and it seems that I have to do an async function, but I have tried and I have not been able to, I am just learning about promises.

Thanks for your help

    
asked by Diego Monsalve 08.11.2018 в 01:46
source

1 answer

0

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);
}
    
answered by 09.11.2018 / 19:10
source