【发布时间】:2020-05-06 21:22:21
【问题描述】:
我正在尝试在 NodeJs 中实现 Customer 对象,并且该实例能够收集其数据。
class CustomerModel extends Model {
public customer
constructor(email:string) {
super();
this.collection = 'customer';
this.customer = await CustomerLayer.getCustomerByEmail(email);
}
}
但我不能有一个异步构造函数。我已经看到在 Javascript 中您可以执行以下操作:
const sleep = () => new Promise(resolve => setTimeout(resolve, 5000));
class Example {
constructor () {
return new Promise(async (resolve, reject) => {
try {
await sleep(1000);
this.value = 23;
} catch (ex) {
return reject(ex);
}
resolve(this);
});
}
}
(async () => {
// It works as expected, as long as you use the await keyword.
const example = await new Example();
console.log(example instanceof Example);
console.log(example.value);
})();
但我认为从构造函数返回数据是不正确的。 从构造函数调用异步方法有什么正确的方法吗?
【问题讨论】:
-
我认为这是关于 async/await 的错误...
-
在这种情况下,我通常会声明一个
init方法,我必须在创建实例后手动调用该方法。我发现它更干净,构造方法应该返回一个实例,而不是一个承诺
标签: javascript node.js mongodb typescript