Reputation: 3809
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.
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()
synchronouslyisCollectionReady
and make a small loop in save
method that wait for isCollectionReady
value to change to true.Is there any better way to do that?
Upvotes: 2
Views: 5263
Reputation: 78860
Definitely don't use a loop; JavaScript is single-threaded, and the async event will never complete.
You can store off the Promise for the initialization instead and simply chain onto it:
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));
}
}
Upvotes: 4