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。
归档时间: |
|
查看次数: |
4640 次 |
最近记录: |