0

I am trying to read a file csv located on the web synchronously. Given the following code

export class AppComponent implements OnInit {
  name = 'Angular';
  apiUrl = 'https://www.techiediaries.com/api/data.json';
  csvFileURL = 'https://www.cdc.gov/coronavirus/2019-ncov/map-data-cases.csv';

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    console.log('start');
    const result = this.fetchData();
    console.log(result);
    console.log('end');
  }

  private async fetchData() {
    let dataset: any;
    const promise = this.httpClient
      .get(this.csvFileURL, { responseType: 'text' })
      .toPromise();
    // console.log(promise);
    await promise
      .then((data) => {
        //console.log('Promise resolved with: ' + JSON.stringify(data));
        dataset = data;
        console.log('inside then statement');

        return data;
      })
      .catch((error) => {
        console.log('Promise rejected with ' + JSON.stringify(error));
      });
    return dataset;
  }
}

What I would like to see in the console is: start data's value inside then statement end

I would also like the fetchdata function to return data

I have also tried the following variants:

  1. http.get(...).subscribe
  2. http.get(...).toPromise

Both execute asynchronously. My current version using async and await The complete code for this problem is here It also executes asynchronously.

I am restricted to Angular 7, by other project constraints.

Tanay
  • 871
  • 1
  • 6
  • 12
Ken
  • 423
  • 6
  • 13
  • 1
    See the aforementioned [suggested duplicate](https://stackoverflow.com/q/14220321/1260204). Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor May 06 '22 at 12:22
  • I agree, Igor, but in this very specific case I cannot allow the program to continue until the file is 'real' file is loaded. The specific use case is the 'real' file contains all of the words that are not allowed and no processing is allowed until that list is in place. – Ken May 06 '22 at 16:18
  • The duplicate is still applicable. You could show some type of loading message / icon / gif until the file content is loaded. How you *should* load the file content is still asynchronous. – Igor May 06 '22 at 16:25
  • Thank you just thought of that based on Aakash's answer look at our timed comments – Ken May 06 '22 at 16:28

1 Answers1

1

Believe me you don't want to do it synchronously, as javascript is single threaded and doing it synchronously will block your user, until you fetch and parse the csv from even clicking a button or doing anything else on your web app.

Code or what you explained can be achieved like below :-

export class AppComponent implements OnInit {
  name = 'Angular';
  apiUrl = 'https://www.techiediaries.com/api/data.json';
  csvFileURL = 'https://www.cdc.gov/coronavirus/2019-ncov/map-data-cases.csv';

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.fetchData.subscribe((csvData) => {
         //what ever part of data you want to use its inside csvData. Remember its text at this moment, with comma separated strings, not a json. as you have sent responseType as text below. If you want a json alread parsed for you remove the second parameter from get call.
    })
  }

  private fetchData() {
    return this.httpClient
      .get(this.csvFileURL, { responseType: 'text' });
}
Aakash Garg
  • 10,649
  • 2
  • 7
  • 25