title: Wait for a function to finish before continuing in javascript
body: <p>What I trying to do is to make the <code>save</code> method to wait for <code>this.collection.create()</code> before executing the save because otherwise it might crash.</p>
  
  <pre><code>class UserRepository extends BaseRepository&lt;User&gt;
  {
      constructor()
      {
          super();
  
          this.collection = this.db.collection('users');
          this.collection.create().then(res =&gt; {
              if (res.code === 200)
              {
                  // collection successfully created
              }
          }).catch(err =&gt; {
              if (err.code === 409)
              {
                  // collection already exists
              }
          });
      }
  }
  
  class BaseRepository&lt;T&gt;
  {
    protected db: Database = Container.get('db');
    protected collection: DocumentCollection;
  
    public save(model: T): void
    {
      this.collection.save(model);
    }
  }
  </code></pre>
  
  <p>And then I can use it like this:</p>
  
  <pre><code>const userRepository = new UserRepository();
  userRepository.save(new User('username', 'password'));
  </code></pre>
  
  <p>I can think of two solutions</p>
  
  <ol>
  <li>Run <code>this.collection.create()</code> synchronously</li>
  <li>Create a property called <code>isCollectionReady</code> and make a small loop in <code>save</code> method that wait for <code>isCollectionReady</code> value to change to true.</li>
  </ol>
  
  <p>Is there any better way to do that?</p>