typescript - 在 javascript 中等待一个函数完成后再继续
我正在尝试做的是让 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。
有什么更好的方法来做这件事吗?
答案#1
绝对不要使用循环;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));
}
}
