I am in need of a solution that will ensure my function waits for a response before proceeding. I want to prevent the response from being empty and ensure that my code waits for the completion of the asynchronous call.
asyncReq(element: any) {
this.conflictData = null;
//For entire 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');
}
})
}
I am seeking assistance in ensuring that the response is not empty and that the code waits for the completion of the asynchronous call. Can someone provide guidance?