代码之家  ›  专栏  ›  技术社区  ›  kunosyn

未使用“回调地狱”语法定义Javascript类属性

  •  0
  • kunosyn  · 技术社区  · 2 年前

    因此,我试图为Roblox API制作一个节点包,在其中,我决定采用面向对象的方法。 当属性(如 <RobloxUser>.id 意外显示为未定义,我添加了控制台。日志语句和API调用正在返回预期值。

    最初,我在类构造函数中添加了一个异步IIFE,以使用异步/等待语法进行调用,我遇到了这个问题。 所以我认为这是一个范围问题或类似的问题,并将我的语法改为“回调地狱”样式的语法,但仍然存在这个问题。

    为了验证我的理论,我设置了一个变量 <RobloxUser>.test = 0 然后使用 console.log ,它按预期打印了0,然后我在回调内部将其设置为2,并在回调外部打印,然后它再次打印了0。

    在我使用Javascript的所有时间里,我从未遇到过类似的问题,如果有人能告诉我如何解决这个问题,我将不胜感激。

    RobloxUser类代码:

    class RobloxUser {
        constructor(response) {
            axios.get(`https://users.roblox.com/v1/users/${response.data.Id}`).then(res => {
                this.username = res.data.name;
                this.displayName = res.data.displayName;
                this.id = res.data.id;    
                    
                this.info = { };
            
                let joinDate = new Date(res.data.created);
                let now = new Date();
                    
                this.info.accountAge = Math.round(Math.abs((joinDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)));
                this.info.isBanned = res.data.isBanned;
            });
    
            axios.get(`https://friends.roblox.com/v1/users/${this.id}/friends/count`).then(res => {
                this.info.friendCount = res.data.count;
            });
            
        
            axios.get(`https://friends.roblox.com/v1/users/${this.id}/followings/count`).then(res => {
                this.info.followingCount = res.data.count;
            });
        
            axios.get(`https://friends.roblox.com/v1/users/${this.id}/followers/count`).then(res => {
                this.info.followerCount = res.data.count;
            });
        
            axios.get(`https://users.roblox.com/v1/users/${this.id}/username-history`).then(res =>  {
                this.info.pastUsernames = res.data.data.map(data => data.name)
            });
        }
    
        getThumbnailURL() {
            
        }
    }
    
    0 回复  |  直到 2 年前