首页 > 解决方案 > 如何加载数据并返回承诺?

问题描述

我有一个模型类:

export class Model {
  constructor(public model: any, public repository: RepositoryService) {
  }

   public hasChildren(id: number) {
        return this.model.childs && this.model.findIndex((opt) => opt.id == id) == -1;
    }

    public getChildren(id: number): Promise<any> {
      return new Promise((resolve, reject) => {
        if (this.hasChildren(id)) {
            resolve(this.model.childs);
        } else {
          this.repository.loadChildren().subscribe((response) => {
            resolve(response);
          })
        }
      });
    }
}

// 创建实例

this.model = new Model(dataModel, this.repositoryService);

如果模型中没有,我尝试获取数据或加载:

this.model.getChildren(value).then((data) => {
   console.log(data);
});

我的问题在于public getChildren(id: number): Promise<any> {}方法。如何在这里正确使用promise?

标签: angulartypescript

解决方案


我认为您不必创建一个 Promise 对象(因为您在任何情况下都不会拒绝它),请尝试以这种方式使用 async/await 语法:

async public getChildren(id: number): Promise<any> {
    if (this.hasChildren(id))
       return (this.model.childs)
    return (await this.repository.loadChildren().toPromise())
}

推荐阅读