Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code:
this.selectedDepartementen.forEach(element => {
this.DepID = element.ID;
if (this.USERSDepIDs.indexOf(this.DepID) == -1) {
this.insertDepartementCoupling(this.DepID, this.USERid, this.AJID, res => {
if (res) {
this.loading = false;
return;
}
this.removeAllFromArray(this.USERSDepIDs, this.DepID, res => {
this.USERSDepIDs = res;
})
})
} else
{
this.updateDepartementCoupling(this.DepID, this.USERid, this.AJID, res => {
if (res) {
this.loading = false;
return;
}
this.removeAllFromArray(this.USERSDepIDs, this.DepID, res => {
this.USERSDepIDs = res;
})
})
}
});
The issue here is that when the function removeAllFromArray
is called to remove the last used DepID
, the foreach loop does not wait for it and continues to execute. It seems like an asynchronous problem, so any suggestions on how to address this would be greatly appreciated.
Thank you in advance!
EDIT
Included is the function insertDepartementCoupling
requested by user Duncan.
async insertDepartementCoupling(DepID, USERid, AJID, callback) {
var test = await this.departementService.insertDepartementCoupling(DepID, USERid, AJID).subscribe(
data => this.mockdata = data,
error => {
this.showMessage("error", "Departement koppeling niet gelukt!", "Departement koppeling niet gelukt, zie console voor meer informatie.");
callback(true);
},
() => {
if (this.mockdata._body) {
this.showMessage("error", "Departement koppeling niet gelukt!", "Contacteer de administrator!");
callback(true);
} else {
this.showMessage("succes", "Departement koppeling geslaagd!", "Gebruiker is gekoppeld aan de departement(en).");
callback(false);
}
});
}