首页 > 解决方案 > Firebase - 使用 once() 检索数据库值的问题

问题描述

我一整天都在遇到这个问题,我正在尝试使用 once() 从我的实时数据库中检索一个值,但它只会给我一个未定义的值或一个无法解决或拒绝的承诺. 我首先根据文档中给出的示例编写了自己的代码片段(尽管我尽了最大努力,但我无法很好理解)但是无论我尝试什么,它都会不断返回“未定义”,这是我的代码写道:

firebase.database().ref('users/' + window.userid + '/MGScore').once('value').then(function (snapshot) {
    window.highscore = snapshot.val();
    // ...
});
console.log(highscore);

最终我决定复制并粘贴文档中使用的示例并更改名称,但它也遇到了返回承诺形式的问题,这些承诺从未自行解决或被拒绝:

function checkHighscore() {
    var userId = window.userid;
    return firebase.database().ref('/users/' + userId).once('value').then(function (snapshot) {
        var highscore = (snapshot.val() && snapshot.val().MGScore) || 'Anonymous';
        // ...
    });
}

我不知道如何处理这个问题,我希望有人可以帮助纠正这个问题。

标签: javascriptfirebasefirebase-realtime-database

解决方案


你可能错误地处理了你的承诺。

firebase.database().ref('users/' + window.userid + '/MGScore').once('value').then(function (snapshot) {
    window.highscore = snapshot.val();
    // ...
});
console.log(highscore);

我假设highscore应该window.highscore像在这个例子中那样它是未定义的?

您正在混合异步/同步工作流程。

// Execute 1st
firebase.database().ref('users/' + window.userid + '/MGScore').once('value')
  .then(function (snapshot) {
      // Execute 3rd
      window.highscore = snapshot.val();
  });

// Execute 2nd
console.log(highscore);

控制台日志将在 thenable 函数之前执行 - 因为它是异步的并等待 firebase 返回响应。

您可能需要将代码重构为如下所示;

baseFunction() {
  // Execute 1st
  firebase.database().ref('users/' + window.userid + '/MGScore').once('value')
    .then(function (snapshot) {
        // Execute 2nd
        window.highscore = snapshot.val();

        // Highscore is set - Call next function
        highscoreSet();
    });
}

highscoreSet() {
  // Execute 3rd
  console.log(highscore);
}

推荐阅读