1

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; });
}
ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
  • `Can't return value from async function. Why?` because it is asynchronous ... `currentUserName().then(....)` is how you should be calling – Jaromanda X May 28 '18 at 08:58
  • `promises.push(promise); return Promise.all(promises).then(function(val) { return val; });` - ahh, the desperate machinations of someone trying to do the impossible ... if I have enough asynchronous layers, it may become synchronous for no apparent reason! – Jaromanda X May 28 '18 at 09:00

1 Answers1

-2

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);
});
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121