0

我有这样的数据库片段:

{
  "users": {
    "usersCount": {
      "count": 61
     ...
     ...
    }
  }
}

我想为这样的变量赋值:

var count = getUserCount();

从这个函数:

function getUsersCount() {
    const ref = db.ref('users/usersCount');
    ref.once("value", function (snapshot) {
        console.log("Value is: ", snapshot.val().count); // There value is right
        return snapshot.val().count;
    }, function (errorObject) {
        console.log("The read failed: " + errorObject.code);
    });
}

但无论我尝试什么,该函数都会返回 undefinde 或对象承诺

4

1 回答 1

0

由于 once() 是异步的,因此不可能使 getUsersCount 同步返回值。它必须返回一个承诺,该承诺会解析为您希望调用者拥有的值。它应该如下所示:

function getUsersCount() {
    const ref = db.ref('users/usersCount');
    return ref.once("value")
    .then(snapshot => {
        console.log("Value is: ", snapshot.val().count); // There value is right
        return snapshot.val().count;
    })
}

调用者使用返回的承诺,如下所示:

getUsersCount()
.then(count => {
    console.log("Count", count);
})
.catch(error => {
    console.log("The read failed", error);
})
于 2020-04-02T15:46:07.610 回答