如何防止底部函数执行直到Angular或Typescript中的前两个完成

时间:2018-12-27 05:52:23

标签: 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));
      }  
}

0 个答案:

没有答案