问题
I want to return name from currentUserName() function, but I got ZoneAwarePromise. Here is my code:
currentUserName() {
var firebaseData = firebase.database().ref('users');
var userid = this.afAuth.auth.currentUser.uid;
var promises = [];
var name;
var promise = firebaseData.orderByKey().once('value').then(function
(snapshot) {
snapshot.forEach(function (childSnapshot) {
if (childSnapshot.key === userid) {
name = childSnapshot.val().displayName;
}
});
return name;
});
promises.push(promise);
return Promise.all(promises).then(function(val) { return val; });
}
回答1:
You should not use Promise.all since there is only one promise to be called, i.e. firebaseData.orderByKey().once('value').
The once() method returns a promise (see the doc) that will be resolved when the asynchronous query to the Real Time Database will be completed.
So your currentUserName() function shall return a promise with the result of the query and you should use then() when you call this function.
So, you should write your function as follows:
function currentUserName() {
var firebaseData = firebase.database().ref('users');
var userid = this.afAuth.auth.currentUser.uid;
return firebaseData.orderByKey().once('value').then(function(snapshot) {
var name;
snapshot.forEach(function (childSnapshot) {
if (childSnapshot.key === userid) {
name = childSnapshot.val().displayName;
}
});
return name;
});
}
and call it as follows:
currentUserName().then(function(snapshot) {
console.log(snapshot);
});
来源:https://stackoverflow.com/questions/50562565/cant-return-value-from-async-function-why