Firebase 上的 JavaScript : something wrong in once ("value"). then();

标签 javascript node.js firebase firebase-realtime-database firebase-admin

enter image description here

为了在Firebase上设置一些云功能,我两天前开始学习Javascript,尝试在“achievementsCount_total” Node 下计算并存储一些数据(数据库结构请参见图)。我已经成功创建了 Node 。然而,该 Node 下存储的数据并不是我所期望的。为了测试发生了什么,我修改了我的代码,如下所示:

const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database. 
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.updateScores = functions.database.ref('/users/{userUID}/achievements')
.onWrite(event => {
  var database=admin.database();
  var achievementsCount_total=new Array();//not important here
  for(var i=0;i<60;i++){achievementsCount_total[i]=0;}//not important here
  var allUsersRef=database.ref("/users");//a list containing all users
  var hasChildren=123;
  allUsersRef.once("value").then(function (snapshot)//SOMETHING WENT WRONG HERE!
  {
    hasChildren=snapshot.hasChildren();//either "true" or "false"
    snapshot.forEach(function(element) 
    {
      // . . . not important here
    });
  });
  return admin.database().ref("/achievementsCount_total").set(hasChildren);      
});

令我惊讶的是, Node “achievementsCount_total”下的值既不是“true”也不是“false”,而是“123”!这意味着出现了问题:

allUsersRef.once("value").then(function (snapshot){. . .});

似乎该函数甚至没有执行(因此变量“hasChildren”的值仍然是123),我不知道为什么。有人知道答案吗?谢谢~

最佳答案

allUsersRef.once("value").then(function (snapshot)//SOMETHING WENT WRONG HERE!
  {
    hasChildren=snapshot.hasChildren();//either "true" or "false"
    snapshot.forEach(function(element) 
    {
      // . . . not important here
    });
  });

是一个异步函数

return admin.database().ref("/achievementsCount_total").set(hasChildren);

不等待它运行,为了解决这个问题,您必须将其返回到 .then()
这应该有效

  return allUsersRef.once("value").then(function (snapshot)//SOMETHING WENT WRONG HERE!
  {
    hasChildren=snapshot.hasChildren();//either "true" or "false"
    snapshot.forEach(function(element) 
    {
      // . . . not important here
    });
    return admin.database().ref("/achievementsCount_total").set(hasChildren);
  });

关于Firebase 上的 JavaScript : something wrong in once ("value"). then();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45647606/

相关文章:

node.js - Yarn - Node Sass 还不支持我当前的环境

firebase - 如何使用 Cloud Firestore 从 Flutter 中的数据快照中获取特定值?

javascript - 对象数组

javascript - Google map - 同一页面上的 2 个 map 无法正常工作

javascript - 兼容node.js的客户端 'require'函数的实现

firebase - 在同一域上使用 firebase 函数的 oAuth 的跨域状态 cookie 问题

javascript - 将 Firebase 与 Redux 绑定(bind)

javascript - Jquery:向下拉菜单添加切换操作

javascript - 如何使用 JavaScript 在页面中生成不同 HTML 标签的列表(必须在 IE6 中工作)

node.js - typescript 中的导入与要求