javascript - 在 JavaScript 中继续之前等待函数完成

标签 javascript typescript design-patterns ecmascript-6 repository-pattern

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

关于javascript - 在 JavaScript 中继续之前等待函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950179/

相关文章:

c++ - "Interface Object"模式。合理的?

javascript - 是否可以通过 Ajax 更改页面源内容变量

javascript - 使用 AngularJS 总结两个 HTML 模板绑定(bind)的内容

javascript - 如何在 HTML 中获取输入类型 Date 并在 angular7 component.ts 文件中使用?

typescript - 为什么 http.post 没有在 Angular 2 中调用我的 Controller

typescript - 类型 'connectedCallback' 上不存在属性 'HTMLElement'

java - 如何在 Java 中创建具有相同类型参数的方法?

javascript - Tomcat Servlet GET 未从 Web 客户端接收参数

javascript - JCanvas 文本中的增量整数

c++ - 合并内容相似但参数不同的函数