Search code examples
angularforeachsubscribe

angular how to wait sucbribe response before for each iterate to next element


I have a pb with my for each loop.

i want to iterate on my user list and for each, i i a api call to do to get some others stats informations. but the loop go to next before the call response of the first element.

I undestand that the for each is synchronous and not the subscribe... so How can i do this ?

here is my code source :

 this.users.forEach(userid => {
    this.httpClient.get(url).subscribe((res: DayStat[]) => {
      res.forEach(y => {
          // do some stuff
          console.log('log1');
      }
    });

    // do some others stuffs
    console.log('log2');
  });

  console.log ('end loop');
  // do some others stuffs;

log order :

end loop;
log1
log2

thanks for your help !


Solution

  • It's happening because http request is asynchronous, this solution should help

    async method() {
      for (const userid of this.users) {
        const res: DayStat[] = await this.httpClient.get(url).toPromise();
        res.forEach(y => {
          // do some stuff
          console.log('log1');
        });
        console.log('log2');
      }
    
      console.log ('end loop');
      // do some others stuffs;
    }