我想做的是让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 是单线程的,异步事件永远不会完成。
您可以存储初始化的 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));
}
}
关于javascript - 在 JavaScript 中继续之前等待函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950179/