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

在构造函数中调用异步函数。

  •  11
  • hashbytes  · 技术社区  · 7 年前

    getUser是异步函数吗?是否需要更长的时间来解决?在我的 someotherclass

    class IdpServer {
        constructor() {
            this._settings = {
                // some identity server settings.
            };
            this.userManager = new UserManager(this._settings);
            this.getUser();
        }
    
        async getUser() {
            this.user = await this.userManager.getUser();
        }
    
        isLoggedIn() {
            return this.user != null && !this.user.expired;
        }
    }
    
    let idpServer = new IdpServer();
    export default idpServer;
    
    
    // another class 
    // import IdpServer from '...'
     class SomeOtherClass {
         constructor() {
            console.log(IdpServer.isLoggedIn());
         }
     }
    
    1 回复  |  直到 7 年前
        1
  •  15
  •   Estus Flask    5 年前

    这是一个与 this popular question

    一旦代码是异步的,就不能以同步方式使用它。如果不需要使用原始承诺,则应使用 async 功能。

    这里的问题是 getUser 提供用户数据的承诺,而不是用户数据本身。构造函数中丢失了承诺,这是反模式。

    解决此问题的一种方法是为 IdpServer ,而API的其余部分将是同步的:

    class IdpServer {
        constructor() {
            ...
            this.initializationPromise = this.getUser(); 
        }
    
        async getUser() {
            this.user = await this.userManager.getUser();
        }
    
        isLoggedIn() {
            return this.user != null && !this.user.expired;
        }
    }
    
    // inside async function
    await idpServer.initializationPromise;
    idpServer.isLoggedIn();
    

    根据应用程序的工作方式, IdpServer.initializationPromise 可以在应用程序初始化时进行处理,以确保依赖于 IdpServer 在准备就绪之前不会初始化。

    另一种方法是 IdpServer 完全异步:

    class IdpServer {
        constructor() {
            ...
            this.user = this.getUser(); // a promise of user data
        }
    
        async getUser() {
            return this.userManager.getUser();
        }
    
        async isLoggedIn() {
            const user = await this.user;
            return user != null && !user.expired;
        }
    }
    
    // inside async function
    await idpServer.isLoggedIn();
    

    预计所有依赖它的单元也将具有异步API。