我正在制作基于 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()
完成其工作,然后再执行另一个函数和另一个函数..
最佳答案
修改getFinanceType
函数为return promise :
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;
});
}
然后从返回的 promise 链:
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
等待所有数据从服务器返回,然后再进行下一步。
关于javascript - 异步完成后如何执行另一个功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56182229/