JavaScript-如何在Firebase中使用Promise? [英] javascript - how to use promises in firebase?

查看:34
本文介绍了JavaScript-如何在Firebase中使用Promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我陷入了一个我不知道如何解决的问题.我问了这个问题,并做了一些努力我们发现Firebase的诺言与普通请求的工作方式不同,我无法正确使用它们.
问题中所述,我m使用Firebase的一些信息填充数组,当我确定数组已填充时,换句话说,当我确定对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 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
})

我正在将这种糟糕的解决方法与睡眠配合使用,以确保外部代码在内部代码之后执行.否则,它将先打印"Out",然后再打印循环中的所有"Found".我尝试过以各种方式将其用于Promise,但仍然无法正常工作.看看此处的文档我找不到任何对我有帮助的东西.

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.

推荐答案

那确实很糟糕.

这应该更接近您的需求:

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
});

这有什么不同:

  1. 它以直接的外观加载每个首选项键(从而消除了加载过多数据的深层嵌套循环的需要.)
  2. 它将所有类别的负载放入一个promise数组中.
  3. 在所有的诺言都解决之后,它会调用您的函数.

这篇关于JavaScript-如何在Firebase中使用Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆