无法从异步函数返回值.为什么? [英] Can't return value from async function. Why?

查看:245
本文介绍了无法从异步函数返回值.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从currentUserName()函数返回名称,但是我得到了ZoneAwarePromise.这是我的代码:

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; });
}

推荐答案

您不应使用Promise.all,因为只有一个诺言可以被调用,即firebaseData.orderByKey().once('value').

You should not use Promise.all since there is only one promise to be called, i.e. firebaseData.orderByKey().once('value').

once()方法返回一个诺言(请参见 doc ),将在对实时数据库的异步查询完成后解决.

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.

因此,您的currentUserName()函数应返回带有查询结果的Promise,并且在调用此函数时应使用then().

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;
        });

    }

并按如下方式调用它:

currentUserName().then(function(snapshot) {
    console.log(snapshot);
});

这篇关于无法从异步函数返回值.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆