0

I am using this native script firebase plugin, which makes me use this function:

getValue() {
     var value;
     firebase.getValue('/companies')
         .then(result => {
             console.log(JSON.stringify(result));
             value = result;
             return result;

         })
         .catch(error => {
             console.log("Error: " + error);
             return error;
         });
     return value;
 }

If I import it in another file and use it like this:

var myValue = this.myFirebaseService.getValue();

If I run it the first time it returns undefined but the second time it returns the value.

My question is how do I make the firebase function return a promise so I can make my second statement wait for it.

NayoR
  • 702
  • 6
  • 13
Stel Dare
  • 53
  • 10

2 Answers2

0

You can initialize myValue after the result has been received from the then block.

Something like this:

var myValue;

function getValue() {
  return firebase.getValue('/companies');
}

myValue = getValue().then(result => {
    const value = JSON.stringify(result);
    console.log(value);
    return value;
  })
  .catch(error => {
    console.log("Error: " + error);
  });
}
nashcheez
  • 5,067
  • 1
  • 27
  • 53
0

The firebase function you're referring to is returning a promise. That's why you can use .then and .catch after calling the getValue function.

If you return the firebase promise from getValue(), like this:

getValue(){
  return firebase.getValue('/companies');
}

You'll be able to call getValue() whenever you like, but you'll have to execute the code after getValue() (which is a promise) is resolved. Like so:

getValue().then(function(value) {
  console.log(value);
});

I would read up on promises if you don't understand this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

James Moran
  • 624
  • 1
  • 7
  • 14