在使用.set()更新之前读取要比较的数据

时间:2016-12-11 02:21:19

标签: javascript firebase firebase-realtime-database

我试图在一个简单的JavaScript游戏中跟踪firebase数据库中的最高分。我想检查用户的分数(javascript变量)是否大于数据库的直接子项'highscore'的当前值。

在firebase文档中,可以使用以下内容返回值:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
  updateStarCount(postElement, snapshot.val());
});

问题是回调仅在数据更新时运行,但我想在更新之前比较数据。

有解决方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Firebase的transaction()方法来实现此目的。例如,您可以执行以下操作:

var latestScore = 99;

starCountRef.transaction(function(savedHighScore){
    if(savedHighScore === null || latestScore > savedHighScore){
        return latestScore;  // will update starCountRef with this value
    }else{
        return;  // nothing to update
    }        
});

查看文档以获取更完整的示例,包括错误处理。

相关问题