簡體   English   中英

代碼在等待 angular 中的異步調用響應之前調用

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

我需要我的部分電話等到響應到來。 我需要一種方法,以便響應不會為空,並且代碼將等待上述異步代碼響應。

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');
    }
  })
}

注意我需要一種方法,以便響應不會為空,並且代碼將等待上述異步代碼響應。 有人可以幫忙嗎?

您的問題是forEach async/await 與 forEach 不太兼容

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

把它改成for就可以了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM