Skip to content Skip to sidebar Skip to footer

Javascript - How To Use Promises In Firebase?

Lately I've been stuck with a problem that I don't know how to solve. I asked this question and after some efforts we've found that Firebase works differently with promises than no

Solution 1:

That's indeed pretty bad.

This should be closer to what you need:

var userTags = [];
var self1 = self;
user_pref.once('value', function(preferenze) { 
  var promises = [];
  preferenze.forEach(function(t) {
    promises.push(ref.child(t.key).once('value'));
  });
  Promise.all(promises).then(function(snapshots) {
    snapshots.forEach(function(snapshot) {
      if (snapshot.exists()) {
        userTags.push(snapshot.key);
      }
    });
  })
  this.myTags = userTags
  this.findPoiByTag(this.myTags) //method I have to call when finished
});

What this does differently:

  1. It loads each preference key with a direct look (removing the need for a deeply nested loop that was loading way too much data).
  2. It puts all load of the categories into an array of promises.
  3. It then calls your function after all promises have resolved.

Post a Comment for "Javascript - How To Use Promises In Firebase?"