等待函数完成,然后在 javascript 中继续

Wait for a function to finish before continuing in javascript

我想做的是让 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);
  }
}

然后我可以这样使用它:

const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));

我可以想到两个解决方案

  1. 运行 this.collection.create()同步
  2. 创建一个名为 isCollectionReady 的 属性 并在 save 方法中创建一个小循环,等待 isCollectionReady 值变为 true。

有更好的方法吗?

绝对不要使用循环; JavaScript 是单线程的,异步事件永远不会完成。

您可以存储用于初始化的 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));
  }
}