I need to iterate through a list and make multiple calls that are dependent on the previous call to finish before iterating the loop. Each function call returns a promise.
My current code just iterates through the list and makes the calls a fast as it can like so:
this.records.forEach(item => {
this.myService.doFirstTask().then(res => {
if (res) {
this.myService.doSecondTask().then(res => {
if (res) {
// do something.
}
});
}
});
});
The problem is that before allowing the .forEach to go to the next item, i need to first wait for myService.doSecondTask()
to complete and return its promise.
I know the solution is to use an async
function with await
, but this is very new to me.
Can anyone provide some help on how to wait for a nested promise to finish, before iterating the .forEach loop?
Is the solution to make the .doSecondTask()
function use async-await
?