0

i've been working with firebase cloud functions and i ran into a trouble.

i wanna retrieve data from my firebase realtime database like this

function get(){
  return firebase.database().ref('/state').once('value', (snapshot) => {
  return snapshot.val();
  });
}

but the proslblem is that when i call get() it immediately returns something like [object Promise] because of the return firebase.database()...

is there a way how to return only snapshot.val() ??

jakubkrnac
  • 11
  • 3

1 Answers1

-1

Javascript is asynchronous. Please read about promises and how it works. Your get() returns a promise you need to wait for it to resolve using then

function get(){
    return firebase.database()
    .ref('/state')
    .once('value', 
        (snapshot) => {
            //This is a arrow function and return is for this callback function passed to once
            return snapshot.val();
         });
}

You can use use callback function inside then to get response from promise.

//Passing a callback function inside then which will print snapshot value
get().
then(val => console.log(val))

With ES7 you can also use async await structure for promises.

Ashish
  • 4,206
  • 16
  • 45