Search code examples
javascriptangularpromiseangular2-services

Angular JS Promise all sequential


I am trying to execute 3 web services with promises, and I need that once all of them are executed, if possible sequentially, I will return the information of the 3 services. I have this.

this is my service

getServices(url: string): Promise < any > {
  return this.http.get(CoordinadoresService.BASEURL + url)
    .toPromise()
    .then(response => {
      return response.json();
    })
    .catch(err => err);
}

this is my component

getOffices() {
  this.oficinas["coordinadores"] = [];
  let data = this.util.getLocalStorage("coordinadores");
  let promises = [];
  if (data != undefined) {
    for (let i = 0; i < Object.keys(data.coordinadores).length; i++) {
      let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;
      promises.push(this.services.getServices(url).then(response => {
          response["coordinador"] = response.coordinador;
          this.oficinas["coordinadores"].push(response)
        },
        err => err));
    }

    Promise.all(promises).then(data => {
      console.log('Both promises have resolved', data);
    });
  }
}

But here he is giving me back undefined. why?

Promise.all(promises).then(data => {
  console.log('Both promises have resolved', data);
});

Thank you.


Solution

  • There are a few issues with your implementation.

    1. First, if you use HttpClient you won't have to map and then call json on the response.
    2. You didn't return from the then of this.services.getServices(url). Hence no response in Promise.all

    Following is the fix.


    import { HttpClient } from '@angular/common/http';
    ...
    constructor(private http: HttpClient) {}
    ....
    getServices(url: string): Promise < any > {
      return this.http.get(CoordinadoresService.BASEURL + url)
        .toPromise();
    }
    
    getOffices() {
      this.oficinas["coordinadores"] = [];
      let data = this.util.getLocalStorage("coordinadores");
      let promises = [];
    
      if (data) {
    
        for (let i = 0; i < Object.keys(data.coordinadores).length; i++) {
          let url = `getOficinas/${data.coordinadores[Object.keys(data.coordinadores)[i]].ip}/${Object.keys(data.coordinadores)[i]}`;
          promises.push(this.getDataFromAPI(url));
        }
    
        Promise.all(promises).then(data => {
          console.log('Both promises have resolved', data);
        });
      }
    }
    
    private getDataFromAPI(url) {
      return this.services.getServices(url)
        .then(
          response => {
            response["coordinador"] = response.coordinador;
            this.oficinas["coordinadores"].push(response)
            return response;
          },
          err => err
        );
    }