I have two methods in both I am doing api calls. Method one is calling out method 2 and should continue with its process after method 2 api call is finished. I tried to do this with the complete function inside subscription, but I am having the problem that method 2 is contiinuing doing its own work without waiting for method 2 to finish. Can someone tell me where my mistake is?
getPerson() {
this.setSelectedFlag() --> Whenever this finishes continue with method
this.personArray = this.form.controls.person.value;
this.personArray .forEach((id) => {
if (!this.personMap.has(id)) {
this.loading.start();
this.api.getpersonsData({
id,
}).subscribe((response) => {
this.personMap.set(id, response);
this.loading.stop();
});
}
});
this.personMap.forEach((person, id) => {
if (!this.personArray.includes(id)) {
this.personen.delete(id);
}
});
}
setSelectedFlag() {
this.personArray = this.form.controls.person.value;
this.personArray.forEach((id) => {
if (!this.setFlagForPerson.has(id)) {
this.personArraySaving.ids.push(id);
this.api.setSelectedForPerson({
body: this.personArraySaving,
}).subscribe({
next: (data) => {
console.log(data);
},
complete: () => {
return --> I thought this would signal its finish
},
});
}
});
}
Using promises would allow you to let setSelectedFlag() return a promise. After it returns you can continue with the code in getPerson()
getPerson() {
this.setSelectedFlag().then(() => {
// rest of the code.
})
}
setSelectedFlag(): Promise<void> {
return new Promise((resolve) => {
....
complete: () => {
resolve();
}
})
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise