[英]Wait for a function to finish before continuing in javascript
What I trying to do is to make the save
method to wait for this.collection.create()
before executing the save because otherwise it might crash. 我想要做的是使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);
}
}
And then I can use it like this: 然后我可以像这样使用它:
const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));
I can think of two solutions 我可以想到两种解决方案
this.collection.create()
synchronously 同步运行this.collection.create()
isCollectionReady
and make a small loop in save
method that wait for isCollectionReady
value to change to true. 创建一个名为isCollectionReady
的属性,并在save
方法中进行一个小循环,等待isCollectionReady
值更改为true。 Is there any better way to do that? 有什么更好的方法吗?
Definitely don't use a loop; 绝对不要使用循环; JavaScript is single-threaded, and the async event will never complete. JavaScript是单线程的,并且async事件将永远不会完成。
You can store off the Promise for the initialization instead and simply chain onto it: 您可以存储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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.