1

Im having some issues with waiting to get a response. Here is the code
Component.ts on click of search button doSearch() will be called which then fires an http call to get data from a JSON.

doSearch() {
    console.log('reached 1');
    this.getDataFromJson();
    console.log('reached 5');
} 

getDataFromJson(): void {
    this.dataService.getdata().then((data: any) => {
      console.log('reached 3');
      data.forEach(item => {
        //console.log(item[1]);
      });
      console.log('reached 4');
    });
 }

DataService.ts:

Here the actual http call is made to fetch the json. Te json is in the assets/json folder.

datatURL = 'assets/json/data.json';    
async getdata() : Promise<MyData[]> {
    const result= await this.httpClient.get<MyData[]>(this.dataURL).toPromise();
    console.log('reached 2');
    return result;
}

I'm expecting the console to be printed as

  • reached 1
  • reached 2
  • reached 3
  • reached 4
  • reached 5

but instead, the execution order is ( the http call is async with not wait ??)

  • reached 1
  • reached 5
  • reached 2
  • reached 3
  • reached 4

I need to parse the data to get some information before the next block gets executed. How can I achieve this?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
jino john
  • 31
  • 2

0 Answers0