我从firebase检索一些数据,但代码不会等待数据,它只是继续运行,一段时间后它会检索数据。我试着等待异步,但仍然......错了什么?谢谢!
var interlocutor = this.getRandomInterlocutor();
FriendlyChat.prototype.getRandomInterlocutor = async function(){
var numberOfUsers = await this.getNumberOfUsersRef();
console.log('numberOfUsers = ' + numberOfUsers);
var randomIndex = Math.floor(Math.random() * numberOfUsers);
console.log('randomIndex = ' + randomIndex);
var ref = await firebase.database().ref('companies/' + this.company + '/users/');
ref.limitToFirst(randomIndex).limitToLast(1).once('value').then(snapshot =>
{
var user = snapshot.val();
console.log('getRandomInterlocutor = ' + user);
});
}
FriendlyChat.prototype.getNumberOfUsersRef = async function(){
var numberOfUsersRef = await firebase.database().ref('companies/' + this.company + '/countregs');
var numberOfUsers;
numberOfUsersRef.on('value', function(snapshot) {
console.log(snapshot.val());
numberOfUsers = snapshot.val();
return numberOfUsers;
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
答案 0 :(得分:2)
这里有几个问题:
await
正在ref
来电,这不是异步。on('value')
,它会发出一组值,而不是一次读取。这是第二个函数的固定版本,用于演示更好的实践:
FriendlyChat.prototype.getNumberOfUsersRef = async function(){
var numberOfUsersRef = firebase.database()
.ref('companies')
.child(this.company)
.child('countregs');
try {
var snapshot = await numberOfUsersRef.once('value');
return snapshot.val();
} catch (errorObject) {
console.log('The read failed:', errorObject.stack);
}
}