javascript - how to use promises in firebase?

好久不见. 提交于 2021-01-27 23:19:59

问题


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 normal requests, and I couldn't use them properly.
As explained in the question, 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:

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 =>{
  await this.sleep(1000) //----> WORKAROUND
  console.log("Out")
  this.myTags = userTags
  this.findPoiByTag(this.myTags) //method I have to call when finished
})

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 docs here I couldn't find anything that would help me.


回答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.


来源:https://stackoverflow.com/questions/47795594/javascript-how-to-use-promises-in-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!