javascript - 如何防止底部函数在 Angular 或 Typescript 中的前两个完成之前执行
问题描述
我有以下构造函数,它应该一个接一个地执行函数。
问题是该buildStats()
函数甚至在第 1 步和第 2 步中的函数执行之前就已执行,这会导致stats
创建空白对象。
我怎样才能防止这种情况?
export class StatsPage implements OnInit {
crops: Crop[];
crop = {} as Crop;
contracts: Contract[];
contract = {} as Contract;
stats = {} as Stats;
constructor(public navCtrl: NavController, private popoverCtrl: PopoverController,
private cropProvider: CropProvider,
private contractProvider: ContractProvider) {
//initialize the properties else it will throw an error at runtime
this.crops = [];
this.contracts = [];
//STEP 1: FETCH CROPS FROM DB
this.cropProvider.getAllCrops()
.then((crops: Crop[]) => {
this.crops = crops;
console.log("this.crops: " + JSON.stringify(this.crops));
})
.catch(e => console.error(e));
//STEP 2: FETCH CONTRACTS FROM DB. DOES NOT DEPEND ON STEP 1 GETTING FINISHED
this.contractProvider.getAllContracts()
.then((contracts: Contract[]) => {
this.contracts = contracts;
console.log("this.contracts: " + this.contracts);
})
.catch(e => console.error(e));
//STEP 3: DO NOT EXECUTE THIS UNTIL BOTH STEP 1 AND STEP 2 FINISHES
this.buildStats();
}
buildStats() {
//THE VARIABLES HERE DO NOT GET CREATED SINCE THE CONTROL REACHES HERE EVEN BEFORE FUNCTIONS IN STEP 1 AND STEP 2 INITIALIZE THE
//crops and contracts VARIABLES. HENCE THE BELOW for LOOP NEVER GET EXECUTED
console.log("crops:" + this.crops);
console.log("contracts:" + this.contracts);
for (let crop of this.crops) {
console.log("into the for loop....");
this.stats.cropName = crop.cropName;
this.stats.grossMarketable = crop.acres * crop.expectedAPH;
this.stats.aphMarketable = crop.acres * crop.guaranteedAPH;
}
console.log("cropName: " + this.stats.cropName);
console.log("grossMarketable: " + this.stats.grossMarketable);
console.log("aphMarketable: " + this.stats.aphMarketable);
console.log("stats: " + JSON.stringify(this.stats));
}
}
解决方案
推荐阅读
- hardware - 通过 USBASP 对 Atmega32U4 进行编程
- python - 在 Python 中编写正 16 位二进制数的二进制补码
- aws-lambda - 如何从 vpc 中的 lambda 调用 step 函数?
- excel - 批处理文件仅在打开 .csv 文件后运行
- javascript - 无效的数据表格式:必须至少有 2 列
- ruby-on-rails - 引用同一模型的 Rails 活动记录关联
- shopify - 是否可以在 for in loop Liquid Shopify 中添加更多值?
- python - 有没有办法以编程方式解析 instagram ?__a=1 页面?
- apache - 在某些条件下拒绝访问 htaccess 中的文件
- java - 处理草图 - 为什么要创建 32 位和 64 位?