0

I have to await for a subscription in a for loop and then utilize the resultant response outside the loop but it is not awaiting.

function abc() {
    this.array = someValueInitialized;
    this.array.forEach(data => {
       this.apiCall.subscribe(resp => {
         console.log("A");
         data.updatedValue = resp.value;
       });
    });
    console.log("B");
    this.array.updatedValue; //undefined
}

The flow of execution is B then A as its not awaiting.

I tried with .toPromise() as well, but that gives ZoneAwarePromise response.

ayeshas7
  • 81
  • 5
  • Does this answer your question? [How to make multiple http subscribe inside a loop in Angular?](https://stackoverflow.com/questions/68631837/how-to-make-multiple-http-subscribe-inside-a-loop-in-angular) – prnvbn Sep 15 '21 at 10:07

1 Answers1

2

Map the array to an array of observables and use forkJoin

const obs=this.array.map(x=>this.apiCall(x));
forkJoin(obs).susbcribe((resAll:any)=>{
   // ..in resAll[0] you has the response to this.apiCall(this.array[0])..
   // ..in resAll[1] you has the response to this.apiCall(this.array[1])..
     ...
   //so
   resAll.forEach((res:any,index:number)=>{
       this.array[index].updatedValue=res.value
   })
}
prnvbn
  • 700
  • 2
  • 7
  • 25
Eliseo
  • 50,109
  • 4
  • 29
  • 67