title: javascript - how to use promises in firebase?
body: <p>Lately I've been stuck with a problem that I don't know how to solve. I asked <a href="https://stackoverflow.com/questions/47775150/javascript-then-executing-before-the-loop-completes-in-firebase/47775453">this</a> question and after some efforts we've found that Firebase works differently with promises than normal requests, and I couldn't use them properly.<br>
  As explained in <a href="https://stackoverflow.com/questions/47775150/javascript-then-executing-before-the-loop-completes-in-firebase/47775453">the question</a>, I'm filling an array with some informations from Firebase, and I need to call another method when I'm sure the array is filled, in other words when I'm sure the call to Firebase has finished.
  This is my code as I'm using it now:</p>
  
  <pre><code>var user_pref = firebase.database().ref('/users/'+ self.api.email_id+'/preferenze/');
        var ref = firebase.database().ref('/tag/')
  var userTags = [];
  var self1 = self;
  user_pref.once('value', function(preferenze) { 
    preferenze.forEach(function(t) {
      ref.once('value', function(tags) { 
        tags.forEach(function(t1) {
          if (t.key == t1.key) { 
            console.log("Found " + t1.key)
            userTags.push(t1.key)
          }
          return false;
        });
      })
      return false;
    });
  }).then(a =&gt;{
    await this.sleep(1000) //----&gt; WORKAROUND
    console.log("Out")
    this.myTags = userTags
    this.findPoiByTag(this.myTags) //method I have to call when finished
  })
  </code></pre>
  
  <p>I'm using this orrible workaround with sleep to be sure the code outside is executed after the one inside. Without that, it prints "Out" before and then all the "Found" in the loop. I've tried using it with promises in every way, but it still doesn't work. Having a look at the <a href="https://firebase.google.com/docs/functions/terminate-functions?hl=en" rel="nofollow noreferrer">docs here</a> I couldn't find anything that would help me.  </p>