节点js计数器值不会增加

时间:2017-05-23 14:16:50

标签: node.js firebase firebase-realtime-database

所以我的想法是得到teamInfo的实例,每个团队然后获得游戏信息并在匹配时更新游戏信息,我希望计数器在找到的每个匹配上递增,然后最终输出对游戏信息进行的匹配(或更新)总数。

我的代码如下:

let counter = 0;
teams.once("value", teamSnap => {
    teamSnap.forEach(tSnap => {
        games.once("value", gameSnap => {
            gameSnap.forEach(gSnap => {
                if(teamInfo.Name == gameInfo.AwayTeam) {
                    let currGame = games.child(`${gSnap.key}`);

                    currGame.update({
                    "AwayTeam": teamInfo.Name,
                    "AwayId": tSnap.key}),
                    function(error){
                        if (error) {
                             console.log("Data could not be saved." + error);
                        } else {             
                             counter++;
                        }
                    }
                }
            }
        }
    }
}).then(() => {
    console.log("Final Count: " + counter)
});

当我调用console.log("Final Count: " + counter)时它显示为零(0),我不确定为什么它不会增加?!

1 个答案:

答案 0 :(得分:0)

您可以在.update function返回的承诺中更新您的计数器,然后打印您的控制台日志

if(teamInfo.Name == gameInfo.AwayTeam) {
   let currGame = games.child(`${gSnap.key}`);

   currGame.update({
      "AwayTeam": teamInfo.Name,
      "AwayId": tSnap.key})
   .then(() => {
      counter++
      console.log(counter)
   })
   .catch(error => {
     console.log(error)
   })
}

如果您想使用现有代码:

if(teamInfo.Name == gameInfo.AwayTeam) {
   let currGame = games.child(`${gSnap.key}`);

   currGame.update({
      "AwayTeam": teamInfo.Name,
      "AwayId": tSnap.key}),
       function(error){
          if (error) {
               console.log("Data could not be saved." + error);
          } else {             
               counter++;
               console.log(counter) //You should log your counter here...
          }
       }
}