es6 class 的constructor中如何调用 返回promise 的函数
constructor() {
this.logObj = null;
this.getLogObj();
this.log = this.logObj.log;
this.trace = this.logObj.trace;
this.error = this.logObj.error;
}
getLogObj() {
if (!this.logObj) {
this.logObj =await this.writeLog();
}
return this.logObj;
}```
上述的代码: 构造中怎么接收 getLogObj函数的值,求帮忙解答 谢谢!
1 回复
constructor() {
this.logObj = null;
this.getLogObj().then(logobj => {
this.log = logObj.log;
this.trace = logObj.trace;
this.error = logObj.error;
});
}
不过这样写会有问题,建议log trace error都用getter,或者用一个异步的工厂函数来创建实例
class Foo {
constructor(cb) {
this.init().then(() => cb(this));
}
async init() {
const logObj = await this.getLogObj();
this.log = logObj.log;
this.trace = logObj.trace;
this.error = logObj.error;
}
getLogObj() {
return new Promise(r => r(123))
if (!this.logObj) {
this.logObj = this.writeLog();
}
return this.logObj;
}
}
function createFoo() {
return new Promise(res => new Foo(res));
}