0

I have a question regarding setting 'public' variable in JavaScript. Here is my code:

var storeKey;
    firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
      var storeData = snapshot.val();
      if (storeData){
        console.log('exists');
      }else{
        storeKey = firebase.database().ref('stores').push({
          storeName : "store1",
          storeAddress : "Blk 167"
        }).getKey();

        //console.log("STORE " + storeKey);
      }
    });

    console.log("STORE " + storeKey);

I am checking if the address exists before adding new record into Firebase. However, if I put the console.log at the last line, I get undefined. It only returns a value if I print it out inside the else statement.

I wanted to separate the storeKey out before I need that data in other places and I don't want my code to be nested inside the else statement. Any idea how to achieve this?

Michael Armes
  • 1,056
  • 2
  • 17
  • 31

1 Answers1

1

Your function accepts a callback, the console.log is called before the callback, that's why its undefined One way to "solve" it is using promises. e.g.

const deferred = q.defer();
    firebase.database().ref('stores').orderByChild('storeAddress').equalTo('Blk 167').once('value', function(snapshot) {
          var storeData = snapshot.val();
          if (storeData){
            console.log('exists');
          }else{
            storeKey = firebase.database().ref('stores').push({
              storeName : "store1",
              storeAddress : "Blk 167"
            }).getKey();

            deferred.resolve(storeKey);
          }
        });

        deferred.then(console.log)
Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133
  • Hey sorry it was working a while back. But then when I ran the second time, I got this error message 'Promise constructor's argument is not a function' –  Jul 13 '17 at 13:10
  • @EmmaHannah You can use the `q` library. Example updated. e.g. https://github.com/kriskowal/q#using-deferreds – Avraam Mavridis Jul 13 '17 at 13:12
  • But it told me can't find variable Q. How do I define Q? Because I dont see it in the link also –  Jul 13 '17 at 13:16
  • @EmmaHannah you have to import the library into your project, if is browser based project you will have it on the `window` if its node project you will have to `require` it. – Avraam Mavridis Jul 13 '17 at 13:21
  • I solved the promises problem by using the syntax at this site: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise –  Jul 13 '17 at 13:21
  • @EmmaHannah yep, thats another way. Native. – Avraam Mavridis Jul 13 '17 at 13:21
  • Hey how do I actually access the promise and store it as another variable? For instance, userKey.then(console.log); will print out the value. But then I wanted to access it in the later part, when I print out userKey, it gives me [object Object] instead of the value –  Jul 20 '17 at 10:32