Can't return value from async function. Why? [duplicate]

无人久伴 提交于 2019-12-25 02:29:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!