如何使功能返回在firebase中的函数(子快照)中设置的数据 [英] How do I make a function return data that was set within function (child snapshot) in firebase

查看:97
本文介绍了如何使功能返回在firebase中的函数(子快照)中设置的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数据返回到调用具有firebase代码的函数的函数,因为firebase查询的异步和嵌套结构无法返回值,我打算使用此逻辑在chart.js中设置工具提示



这是我的代码:

$ p $ window.onload = function ){
get_data();


函数get_data(){
var data = get_val();
console.log(....+ data);
}

函数get_val(){
var label =10/2/2017;
var Name = localStorage.getItem(VName);
console.log(Name :::+ Name);
var at_val;
var dbref = new Firebase(https://apraisalstaging.firebaseio.com/EmployeeDB/EInfo/);
dbref.once(value)。then(function(snapshot){
snapshot.forEach(function(childsnapshot){
var data = childsnapshot.val();
var Nameval = data.Name; $ b $ if(Nameval == Name){
console.log(Success);
Ikey = childsnapshot.key();
console。 log(Key :::+ Ikey);
var dxRef = new Firebase(https://apraisalstaging.firebaseio.com/EmployeeDB/EApraise/+ Ikey);
dxRef.once (函数(快照)){
snapshot.forEach(function(childsnapshot){
var data = childsnapshot.val();
console.log(data);
if(label == data.Dateval){
console.log(-------> bingo);
at_val = data.Attitude;
console .log(got value:+ at_val);
}
});
})。then(function(){
console.log(In then:+ at_val);
return at_val;
});


$)b

$ b $ div class =h2_lin >解决方案

数据是从Firebase数据库异步加载的。您现在还不能返回尚未加载的值 。直到 async await 关键字变得很常见,您不能让JavaScript等待异步值。



您今天可以得到的最接近的结果是从 get_val()返回一个承诺。然后你的调用代码将是:
$ b $ pre $ get_val()。then(function(data){
console.log ....+ data);
});

为此,您必须实现 get_val()为:

 函数get_val(){
var label =10/2/2017;
var Name = localStorage.getItem(VName)|| 三角洲;
console.log(Name :::+ Name);
var at_val;
var dbref = firebase.database()。ref(EmployeeDB / EInfo /)。orderByChild(Name)。equalTo(Name);
return dbref.once(value)。then(function(snapshot){
var promises = [];
snapshot.forEach(function(childsnapshot){
var data = childsnapshot.val();
var Nameval = data.Name;
Ikey = childsnapshot.key;
var dxRef = firebase.database()。ref(EmployeeDB / EApraise /+ Ikey).orderByChild(Dateval)。equalTo(label);
promises.push(
dxRef.once(value)。then(function(snapshot){
snapshot.forEach (function(childsnapshot){
var data = childsnapshot.val();
at_val = data.Attitude;
});
})。 b $ b console.log(然后:+ at_val);
return at_val;
))
);
})
return Promise.all承诺);
))
}

我对< code $ get_val():
$ b


  • 它使用新的3.x版本Firebase SDK。解决方案也可以使用2.x,我只是不想为此设置一个jsbin。

  • 它填充一个promise列表,一个对于每个 EApraise 记录


  • 它返回一个承诺,当所有的 EApraise 记录被加载。

  • 它使用Firebase查询来查找正确的记录。这消除了检查然后()回调中的值的需要。但更重要的是,它确保只有必要的数据被下载。

    $ b $ p

    为了使最后一点成真,你需要在 Firebase数据库控制台中的规则中添加一些索引定义:

    $ $ $
    $ {
    EmployeeDB:{
    EInfo :{
    .indexOn:Name
    }
    EApraise:{
    $ eid:{
    .indexOn:Dateval
    }
    }
    }
    }
    }

    这里带有工作代码的jsbin: http://jsbin.com/jawamilawo /编辑?js,控制台


    I want to return data to function that calls a function with firebase code, because of the asynchronous and nested structure of firebase queries it is not able to return values, I intend to use this logic to set tool tips in chart.js

    Here is my code:

    window.onload = function() {
        get_data();
    }
    
    function get_data() {
        var data = get_val();
        console.log("...." + data);
    }
    
    function get_val() {
        var label = "10/2/2017";
        var Name = localStorage.getItem("VName");
        console.log("Name:::" + Name);
        var at_val;
        var dbref = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EInfo/");
        dbref.once("value").then(function(snapshot) {
            snapshot.forEach(function(childsnapshot) {
                var data = childsnapshot.val();
                var Nameval = data.Name;
                if (Nameval == Name) {
                    console.log("Success");
                    Ikey = childsnapshot.key();
                    console.log("Key:::" + Ikey);
                    var dxRef = new Firebase("https://apraisalstaging.firebaseio.com/EmployeeDB/EApraise/" + Ikey);
                    dxRef.once("value").then(function(snapshot) {
                        snapshot.forEach(function(childsnapshot) {
                            var data = childsnapshot.val();
                            console.log(data);
                            if (label == data.Dateval) {
                                console.log("-------> bingo");
                                at_val = data.Attitude;
                                console.log("got value:" + at_val);
                            }
                        });
                    }).then(function() {
                        console.log("In then:" + at_val);
                        return at_val;
                    });
                }
            })
        })
    }
    

    解决方案

    Data is loaded from the Firebase Database asynchronously. You cannot return a value now that hasn't been loaded yet. And until the async and await keywords are commonplace, you cannot make JavaScript wait for the async value.

    The closest you can get today is to return a promise from get_val(). Then your calling code will be:

    get_val().then(function(data) {
      console.log("...." + data);
    });
    

    To do this you'll have to implement get_val() as:

    function get_val() {
      var label = "10/2/2017";
      var Name = localStorage.getItem("VName") || "delta";
      console.log("Name:::" + Name);
      var at_val;
      var dbref = firebase.database().ref("EmployeeDB/EInfo/").orderByChild("Name").equalTo(Name);
      return dbref.once("value").then(function(snapshot) {
        var promises = [];
        snapshot.forEach(function(childsnapshot) {
          var data = childsnapshot.val();
          var Nameval = data.Name;
          Ikey = childsnapshot.key;
          var dxRef = firebase.database().ref("EmployeeDB/EApraise/" + Ikey).orderByChild("Dateval").equalTo(label);
          promises.push(
            dxRef.once("value").then(function(snapshot) {
              snapshot.forEach(function(childsnapshot) {
                var data = childsnapshot.val();
                at_val = data.Attitude;
              });
            }).then(function() {
              console.log("In then:" + at_val);
              return at_val;
            })
          );
        })
        return Promise.all(promises);
      })
    }
    

    I made a few changes to get_val():

    • it uses the new 3.x versions of the Firebase SDK. The solution could also work with 2.x, I just didn't feel like setting up a jsbin for that.

    • it populates a list of promises, one for each of the EApraise records

    • it returns a promise that resolves when all the EApraise records are loaded.

    • it uses Firebase queries to find the correct record. This removes the need for checking the values in the then() callbacks. But more importantly it ensures that only the necessary data is downloaded.

    To make that last point true, you need to add a few index definitions to the rules in your Firebase Database console:

    {
      "rules": {
        "EmployeeDB": {
          "EInfo": {
              ".indexOn": "Name"
          }
          "EApraise": {
            "$eid": {
              ".indexOn": "Dateval"
            }
          }
        }
      }
    }
    

    Here a jsbin with the working code: http://jsbin.com/jawamilawo/edit?js,console

    这篇关于如何使功能返回在firebase中的函数(子快照)中设置的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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