0

I have the following constructor which is supposed to execute functions one after another.

The problem is that buildStats() function gets executed even before the functions in Step 1 and Step 2 get executed which results in blank stats object creation.

How can I prevent this ?

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));
      }  
}
Nital
  • 5,784
  • 26
  • 103
  • 195

0 Answers0