【发布时间】:2018-04-20 21:48:34
【问题描述】:
我试图做的是让save 方法在执行保存之前等待this.collection.create(),否则它可能会崩溃。
class UserRepository extends BaseRepository<User>
{
constructor()
{
super();
this.collection = this.db.collection('users');
this.collection.create().then(res => {
if (res.code === 200)
{
// collection successfully created
}
}).catch(err => {
if (err.code === 409)
{
// collection already exists
}
});
}
}
class BaseRepository<T>
{
protected db: Database = Container.get('db');
protected collection: DocumentCollection;
public save(model: T): void
{
this.collection.save(model);
}
}
然后我可以这样使用它:
const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));
我能想到两种解决方案
- 同步运行
this.collection.create() - 创建一个名为
isCollectionReady的属性,并在save方法中创建一个小循环,等待isCollectionReady值更改为true。
有没有更好的方法来做到这一点?
【问题讨论】:
-
您需要阅读大量关于 Javascript 中的异步操作、node.js 的事件驱动单线程特性、promise 以及
async和await的使用。在 Javascript 中,您并没有真正“等待函数完成”。相反,您使用 promise 或回调在完成时收到通知。
标签: javascript typescript design-patterns ecmascript-6 repository-pattern