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

has*_*tes 6 javascript asynchronous ecmascript-6 identityserver4

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());
     }
 }
Run Code Online (Sandbox Code Playgroud)

Est*_*ask 10

这是一个与此流行问题有关的问题

代码一旦异步,就不能以同步方式使用。如果不需要使用原始承诺,则应使用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();
Run Code Online (Sandbox Code Playgroud)

根据应用程序的工作方式,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();
Run Code Online (Sandbox Code Playgroud)

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