javascript - 异步完成后如何执行另一个功能?
问题描述
我正在制作基于 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
函数以返回承诺:
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
等待所有数据从服务器返回,然后再进行下一步。
推荐阅读
- python-3.x - 如何使用 urllib 和 Python3 访问 JSON 元素
- angular - ThreeJS / Angular - “场景未定义”
- angular - NativeScript Angular ngClass 不起作用
- reactjs - React-Leaflet 在开发环境中渲染本地图块
- c++ - 如何获取指针类型而不是 UNKNOWN
- akka-http - 如何为从 ByteString 创建的 HttpRequest/HttpEntity 设置块大小
- c# - 以下用于排序的 EF MVC 5 代码如何工作?
- redis - Redis - 你可以根据值进行查询吗?
- javascript - 如何在测试环境之外运行 webdriver-io 并仍然访问全局变量 $ 和 $$?
- php - 无法将下拉字符串值与 yii2 中的 int(用户角色)进行比较