Reputation: 43
I am currently learning how async works, while working on a small project using Firebase databases. As far as I understand await should pause the function until a promise is resolved, but in my case it's not waiting for that.
I've shortened 2 functions I used to try and test this:
async findUser(id) {
await this.firebase.findUserData(id).then(
value => {
console.log('finduser stopped waiting');
return value;
}
)
}
async findUserData(userId){
console.log('firebase started looking for user');
firebase.database().ref('/users/' + userId).once('value').then(function(snapshot){
let user = (snapshot.val());
console.log('found: ' + user);
return user;
});
}
The console output looks like this: (not allowed to embed images yet)
It's running findUser first, followed by the Firebase call, but does not wait for that promise to complete before returning a value. Found user id prints last.
I'm sure I'm doing something really dumb here, but I couldn't figure it out for a while now and have nobody else to turn to.
Sorry if the question is poorly written. First time posting around here. Welcome any feedback!
Upvotes: 4
Views: 1468
Reputation: 138247
You should not mix await
and then
s. Then you also don't forget to await a promise (you never await / return the Promise returned by .once):
async findUserData(userId){
console.log('firebase started looking for user');
const snapshot = await firebase.database().ref('/users/' + userId).once('value');
let user = (snapshot.val());
console.log('found: ' + user);
return user;
}
async findUser(id) {
const value = await this.firebase.findUserData(id);
console.log('finduser stopped waiting');
return value;
}
Upvotes: 6