Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them into an array before making the API call.
for (let a = 0; a < perfCriteria.length; a++) {
const element = perfCriteria[a];
let newObject = Object.assign({}, paramObject)
newObject.performanceCriteria = element.performanceCriteriaId
for (let b = 0; b < element.performanceIndicators.length; b++) {
const element2 = element.performanceIndicators[b];
let newObject2 = Object.assign({}, newObject)
newObject2.performanceIndicator = element2.performanceIndicatorId
newObject2.numberTarget = element2.divisionTarget ? element2.divisionTarget : ""
newObject2.targetDetails = element2.targetDetails
for (let c = 0; c < element2.targetDetails.length; c++) {
const element = element2.targetDetails[c];
element2.targetDetails[c].individualAccountable = element.individualAccountable.map(function(row){
return row._id
})
}
divTargetArray.push(newObject2)
}
}
this.DivisionTarget.create(divTargetArray).subscribe(result =>{
console.log('result', result)
if(result.success){
this.appComponent.showLoadingIndicator = false;
this.router.navigate(['/index/app/performanceManagement/divisionTargets']);
this.toastService.openSnackBar(result.message, "success");
}else{
this.appComponent.showLoadingIndicator = false;
this.toastService.openSnackBar(result.message, "danger");
}
}, error => {
this.appComponent.showLoadingIndicator = false;
this.toastService.openSnackBar(error, "danger");
});
Despite the functionality of the code, there have been instances where it doesn't wait for the For loop to finish before proceeding with submitting the data to the API. Is there a method or technique that can ensure the completion of the For loop before moving forward with the API submission?