我尝试做的是让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。有没有更好的方法呢?
答案 0 :(得分:4)
绝对不要使用循环; JavaScript是单线程的,异步事件永远不会完成。
您可以将Promise存储起来进行初始化,然后直接链接到它:
class UserRepository extends BaseRepository<User>
{
constructor()
{
super();
this.collection = this.db.collection('users');
this._initPromise = this.collection.create().then(res => {
if (res.code === 200)
{
// collection successfully created
}
}).catch(err => {
if (err.code === 409)
{
// collection already exists
}
});
}
ensureInitialized() {
return this._initPromise;
}
}
class BaseRepository<T>
{
protected db: Database = Container.get('db');
protected collection: DocumentCollection;
public ensureInitialized() {
return Promise.resolve();
}
public save(model: T): Promise<void>
{
return this.ensureInitialized()
.then(() => this.collection.save(model));
}
}