首页 > 解决方案 > 如何防止底部函数在 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));
      }  
}

标签: javascriptangulartypescript

解决方案


推荐阅读