首页 > 解决方案 > 异步完成后如何执行另一个功能?

问题描述

我正在制作基于 angularjs 和 typescript 的应用程序,在构造函数中我调用加载函数,例如,

private load(): angular.IPromise<void> {

    const progTokInit: string = 'initial';
    this.$scope.progress.start(progTokInit);

    return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => { 
         //Doing foreach and sending employeeModel
         //  to get the financetype of the person
         resp.employeeRates.forEach(employeeModel => this.getFinanceType(employeeModel));

         this.refreshCostRate(...resp.employeeRates)
          .then(() => // Another Function )
          .then(() => // Yet Anothoer Function )
     })
}

在这里,我需要获取一个人的财务类型,如果我发送成本中心号码,我将获得数据,所以我在getFinanceType()函数中给出了这样的数据,

private getFinanceType (employeeModel:any) {
    this.costService.getFinanceType(employeeModel.person.cost_center.getValue()[0])
        .then((result) => {
          console.log('res ', result);
          employeeModel.financeType = result;
          return result;
        });
}

上述函数是异步的,因此在获取所有相关数据之前会有最大延迟,直到那时我需要等待移动到下一步,即,this.refreshCostRate(...resp.employeeRates)只有当当前getFinanceType ()函数完全完成其任务时,我才需要调用。

我尝试过使用async/await 之类的,

private async getFinanceType (employeeModel:any) {
    await return this.costService.getFinanceType(employeeModel.person.cost_center.getValue()[0])
        .then((result) => {
          console.log('res ', result);
          employeeModel.financeType = result;
          return result;
        });
}

但没有任何帮助,即使此数据未完成,执行仍在继续,因此我无法employeeModel.financeType在正确的时间设置数据。

请帮助我处理这种情况,等待它getFinanceType()完成它的工作,然后在执行另一个函数和另一个函数之后..

标签: javascriptjqueryangularjstypescriptpromise

解决方案


修改getFinanceType函数以返回承诺:

private getFinanceType (employeeModel:any) {
    var value = employeeModel.person.cost_center.getValue()[0]
    return this.costService.getFinanceType(value)
      .then((result) => {
        console.log('res ', result);
        employeeModel.financeType = result;
        return result;
    });
}

然后从返回的承诺中链接:

private load(): angular.IPromise<void> {

    const progTokInit: string = 'initial';
    this.$scope.progress.start(progTokInit);

    return this.entityService
      .load(this.$scope.projectRevisionUid)
      .then(resp => { 
         //Doing foreach and sending employeeModel
         //  to get the financetype of the person
         var promiseArr = resp.employeeRates.map(_ => this.getFinanceType(_));
         promiseArr.push(resp);
         return $q.all(promiseArr);
      })
      .then(financeTypeArr) {
         var resp = financeTypeArr.pop();   
         return this.refreshCostRate(...resp.employeeRates)
          .then(() => // Another Function )
          .then(() => // Yet Anothoer Function )
     })
}

用于$q.all等待所有数据从服务器返回,然后再进行下一步。


推荐阅读