vendredi 20 avril 2018

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.

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

  1. Run this.collection.create() synchronously
  2. Create a property called isCollectionReady 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?

Aucun commentaire:

Enregistrer un commentaire