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

哈希字节

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());
     }
 }
那将是烧瓶

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

一旦代码是异步的,就不能以同步方式使用它。如果不需要使用原始承诺,则应使用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。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章