在构造函数中调用异步函数. [英] calling an async function in the constructor.
问题描述
getUser是一个异步函数?是否需要更长的时间解决?它将始终在我的someotherclass
中返回正确的值.
getUser is an async function? if it is going to take longer time to resolve? is it going to always return the right value in my 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
函数执行所有控制流程.
Once a code is asynchronous, it cannot be used in synchronous manner. If the use of raw promises is unwanted, all control flow should be performed with async
functions.
这里的问题是getUser
提供了对用户数据的承诺,而不是用户数据本身.承诺在构造函数中丢失了,这是反模式.
The problem here is that getUser
provides a promise of user data, not user data itself. A promise is lost in constructor, and this is antipattern.
解决问题的一种方法是为IdpServer
提供初始化承诺,而其余的API将是同步的:
One way to solve the problem is to provide initialization promise for IdpServer
, while the rest of API will be synchronous:
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
的所有单元在准备就绪之前不会被初始化.
Depending on how the application works, IdpServer.initializationPromise
can be handled on application initialization to guarantee that all units that depend on IdpServer
won't be initialized until it's ready.
另一种方法是使IdpServer
完全异步:
Another way is to make IdpServer
entirely asynchronous:
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.
It's expected that all units that depend on it will also have asynchronous API.
这篇关于在构造函数中调用异步函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!