Code is calling before waiting for response of asynchronous call in angular

Viewed 45

I need my part of call to wait till the response comes. I need a way so that response will not be empty and code will wait for above asynchronous code response.

asyncReq(element: any) {
  this.conflictData = null;
  //For all day
  let startDate: any;
  let endDate: any;
  startDate = this.easternToUtc.transform(moment(element.START_TIME).format('YYYY/MM/DD 00:00:00'), this.selectedTimeZone);
  endDate = this.easternToUtc.transform(moment(element.END_TIME).format('YYYY/MM/DD 23:59:59'), this.selectedTimeZone);
  return new Promise((resolve, reject) => {
    let requestPayload = zipObj(['USER_ID', 'AMENITY_TYPE_ID', 'AMENITY_ID', 'START_TIME', 'END_TIME', 'BUILDING_ID', 'AMENITY_NAME'], [element.USER_ID, element.AMENITY_TYPE_ID, element.AMENITY_ID, startDate,
      endDate, element.BUILDING_ID, element.AMENITY_NAME
    ]);
    this.http.post(`${environment.reservationValidation}`, requestPayload).pipe(take(1)).subscribe(e => {}, (e: any) => {
      console.log(e);
      element.ERROR_TYPE = e.error ? .message;
      element.HAS_ERROR = true;
      this.conflictData = e.error ? .reservationdata;
    })
  })
}

async validateRecords(data: any, step: any): Promise < void > {
  return new Promise(async(resolve, reject) => {
    try {
      data.forEach(async(element: any) => {
        await this.asyncReq(element);
      })
      // this.errorCount = await this.finalData.filter(a=>a.HAS_ERROR).length;
      // console.log(this.errorCount,"error Count");
      console.log(this.finalData);
      const errors = await this.finalData.filter((ele) => ele.HAS_ERROR)
      console.log("errors", errors); // always returning empty array though the value of ele.HAS_ERROR is true bcoz this is calling before waiting for response.
      this.errorCount = errors.length; // this is always giving 0 
      setTimeout(() => {
        this.step = step;
      }, 800)
    } catch {
      console.log('Some Error');
    }
  })
}

Note I need a way so that the response will not be empty and code will wait for the above asynchronous code response. Can someone help?

1 Answers

Your problem is the forEach async/await is not so compatible with forEach

data.forEach(async(element: any) => {
    await this.asyncReq(element);
})

change it to for and it will work

Related