异步函数返回Angular中的ZoneAwarePromise

时间:2018-05-28 20:25:49

标签: javascript angular firebase

我有函数currentUserName()应返回name但返回包含__zone_symbol__value的ZoneAwarePromise和正确的数据。

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

函数调用:

this.currentUserName().then(function (snapshot) { return snapshot; }));

1 个答案:

答案 0 :(得分:0)

为什么不使用承诺?

currentUserName(): Promise<any> {
        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;

}

并像这样称呼它

this.currentUserName().then(function(name) { console.log(name) }));