首页 > 解决方案 > 从回调函数返回一个值

问题描述

我正在使用 on() 方法在我们的数据库中检索数据快照,但我需要能够存储此快照值,以便可以使用它来检索另一个单独的快照。

这是我们的数据库的样子: Firebase 实时数据库

有一个用户节点和一个单独的设备节点。每个用户都有一个子“设备”,它是与该用户关联的设备列表。我扩展的用户只有一台设备。

我想要做的是存储这个 deviceID,然后进行单独的查询以在“设备”节点中找到该设备。这是我的代码的样子:

let uid = fireBaseUser.uid; 
//get a reference to the database
let database = firebase.database();
let ref = database.ref("users/").child(uid).child("devices"); 
ref.on("value", getData);

然后回调函数如下所示:

function getData(data)
{ 
  currentDevice = Object.keys(data.val())[0];
  console.log("current device: " + currentDevice); 
}

这只是抓取用户设备列表中的第一个设备并将其打印到控制台。我试图弄清楚如何返回这个值,以便在从设备树获取数据时可以使用它。哪个,我猜,看起来像这样:

let deviceRef = database.ref("devices/").child(retrievedValue);
deviceRef.on("value", getData2);

retrievedValue 是我从第一个查询中获得的 deviceID。

是否可以在javascript中执行此操作,还是有更好的方法?我知道已经有人问过类似的问题,但是我发现我在网上看到的所有示例都非常令人困惑,对我没有多大帮助。任何帮助都将非常感激,因为我有点坚持这一点。谢谢!

标签: javascriptfirebasefirebase-realtime-database

解决方案


你必须学习 Promise 和异步编程。这里有两种方法可以做你想做的事:

let uid = fireBaseUser.uid; 
//get a reference to the database
let database = firebase.database();
let ref = database.ref("users/").child(uid).child("devices"); 
ref.once("value").then((data) {
  currentDevice = Object.keys(data.val())[0];
  console.log("current device: " + currentDevice); 
  let deviceRef = database.ref("devices/").child(currentDevice);
  return deviceRef.once("value");
}).then((value) {
  console.log("value is " + value);
})

或使用异步/等待:

let uid = fireBaseUser.uid; 
//get a reference to the database
let database = firebase.database();
let ref = database.ref("users/").child(uid).child("devices"); 
let data = await ref.once("value")
currentDevice = Object.keys(data.val())[0];
console.log("current device: " + currentDevice); 
let deviceRef = database.ref("devices/").child(currentDevice);
let value = await deviceRef.once("value");
console.log("value is " + value);

我对第二个更有信心,因为我在没有测试的情况下打字。

这些链接将有助于开始学习这些东西: https ://firebase.googleblog.com/2016/01/keeping-our-promises-and-callbacks_76.html https://firebase.google.com/docs/functions/终止函数

编辑:我通过替换为修复了上面的on代码once。但是现在这不再监听数据库中的变化了。要更正您的代码以监听用户的设备更改:

let uid = fireBaseUser.uid; 
//get a reference to the database
let database = firebase.database();
let ref = database.ref("users/").child(uid).child("devices"); 
ref.on("value", getData);

function getData(data) // may need to place this before the code above
{ 
  currentDevice = Object.keys(data.val())[0];
  console.log("current device: " + currentDevice); 
  let deviceRef = database.ref("devices/").child(currentDevice);

  // no need to listen to this, as a change in one device would fire 
  // for every user. you probably don't want that. 
  deviceRef.once("value", (data) { 
    console.log(data);
  });
}

推荐阅读