代码没有更新,如何知道迭代是否发生?

Code not getting updated and how to know whether iteration is happening?

我的 firebase-database 结构如下:

还有我在node.js中的函数代码:

exports.addFunction = functions.database
    .ref('/Users/{uid}/GyroScope X-axis')
    .onWrite(event => {

var add = 0;
const addGyroX = admin.database().ref('/GyroXaddition');
const userRef = event.data.adminRef;  

userRef.once('value').then(snapshot => {
  snapshot.forEach(childrensnap => {
      var reading = childrensnap.key;
      var childData = reading.val();
      add = add+childData;
      return addGyroX.set(childData); 
    });
  });
});

我的计划是迭代 GyroScope X 轴的值,并在迭代时将值更新为新创建的路径 (GyroXaddition)。我没有收到任何错误,但它也没有更新。

您提供的代码肯定无法运行,并且可能会抛出很多错误。以下是我注意到的几件事:

  1. 你没有返回你的 Promise,这会给你带来麻烦。
  2. 你的forEach位置不对,需要在函数体内调用
  3. 您的 set 正在引用来自不同范围的数据(同样,如果您尝试迭代多个值,.set 将只使用最后一个值)。
  4. event.data.adminRef 是正确的大小写。
  5. snapshot.key 不是 snapshot.key()

此代码段修复了一些 问题,但我不确定您正在尝试做什么才能让您一路走来。

return userRef.once('value').then(snap => {
  var sets = [];

  snap.forEach(childsnapshot => {
    var reading = childsnapshot.key;
    var childData = reading.val();
  });
});

因为您没有等待对 return 值的异步调用。抓取您的数据并设置 childData 时,花费的时间比平时长。使用异步编程时,多个线程将同时运行。在您的代码中,值 addGyroX 被 returned,即使 childData 不存在。因此,为了return正确的值,请使用这段代码

exports.addFunction =
functions.database .ref('/Users/{uid}/GyroScope X-axis') .onWrite(event => { 
  const addGyroX = admin.database().ref('/GyroXaddition'); 
  const userRef = event.data.adminref;
  userRef.once('value').then(forEach(childsnapshot => { 
    var reading = childsnapshot.key(); 
    var childData = reading.val(); 
    return addGyroX.set(childData);
  })
); 
});

这样,addGyroX 将仅在收到值时 return。