angularrxjsangular-services

Synchronize call to 2 methods


In a component (or service) I call to Main method which calls to 2 other private methods.

export class MyService
{
    private Stage1 (N : number)
    {
      console.log ('-->Stage1');
      for (let i=0;i<N;i++)
      {
          //Send HTTP request
      }
      console.log ('<--Stage1');
    }
    
    private Stage2 (N: number)
    {
      console.log ('-->Stage2');
      for (let i=0;i<N;i++)
      {
           //Send HTTP request
      }
      console.log ('<--Stage2');
    }
    
    public Main ()
    {
        this.Stage1 (5);    
        this.Stage2 (7);
    }
}

I want that Stage2 will be called only after Stage1 is completed. The goal is to get the following output:

-->Stage1
<--Stage1
-->Stage2
<--Stage2

What should I add to my code? I tried:

async public Main ()
{
    await this.Stage1 ();    
    await this.Stage2 ();
}

But this concept failed.


Solution

  • You could use Promise and put them into an array of promises and wait for all promises to complete using the Promise.all method

    export class MyService {
    constructor(private http: HttpClient) {}
    
    private async Stage1() {
        console.log('-->Stage1');
        await this.sendHttpRequests(); // Simulated async HTTP requests
        console.log('<--Stage1');
    }
    
    private async Stage2() {
        console.log('-->Stage2');
        await this.sendHttpRequests();
        console.log('<--Stage2');
    }
    
    public async Main() {
        await this.Stage1();
        await this.Stage2();
    }
    
    private async sendHttpRequests() {
        const requests = [
            this.http.get('https://api.example.com/data1').toPromise(),
            this.http.get('https://api.example.com/data2').toPromise(),
            this.http.get('https://api.example.com/data3').toPromise()
        ];
        await Promise.all(requests); // Wait for all HTTP calls to complete
    }
    }