简体   繁体   中英

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?

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));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM