0

In an Angular app, i have a component that subscribes to an Observable in a service.

this.listService.listApi(params)
          .subscribe(
            response => this.listServiceResponse(response),
            error => this.serviceError = <any>error);

In the service, the observable makes an http request. I need to loop through the response and construct a results array based on some calculations which will be what is ultimately returned to the component.

For clarity, I have simplified the resulting array here as mine is much more complex, but the point here is that i achieved this using the map function. Here are the relevant parts of the methods in the service:

listApi(params:any) Observable<any[]> {
    ...
    return this.http.get(params.url, ampOptions)
                        .map(data => this.listExtract(response, params))
                        .catch(this.handleError);
}
listExtract(response:any, params:any) {

  let successArray:any = [];
  let failedArray:any = [];

  let filteredArray:any = [];

  let itemFound:boolean = false;

  response.map((item, index) => {
    if(item.rank > params.rank) {
      filteredArray.push(item);
      if(item.id === params.id) {
        itemFound = true;
      }
    }
  });

  // are the following lines guaranteed to wait for the map function to finish?

  if(itemFound === true) {

    // do some additional calculations and construct the successArray
    // then push the filteredArray onto my successArray;

    successArray.push(filteredArray);

    return successArray;

  } else {

    // do some additional calculations and construct the failedArray
    // then push the filteredArray onto my failedArray;

    failedArray.push({flag:'failed',id:params.id});
    failedArray.push(filteredArray);

    return failedArray;
  }

}

This appears to be working correctly, but is it safe to assume that the map function is synchronous and the lines that follow are guaranteed to execute only after the map function completes?

DevMike
  • 1,630
  • 2
  • 19
  • 33

1 Answers1

0

If response is guaranteed to be an array - in order to not blow up your code - then yes, its map() function is synchronous.

Alexander Leonov
  • 4,694
  • 1
  • 17
  • 25