为了在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/