0

I am trying to convert CSV from a CSV file to JSON.

I have the following code

(async() => {



csvToJson().fromStream(request.get("https://raw.githubusercontent.com/dsfsi/covid19za/master/data/covid19za_provincial_cumulative_timeline_confirmed.csv"))
.then(source => {

  let latest_provinces_confirmed = source;
});

console.log(latest_provinces_confirmed)
...

and when I run it, I get UnhandledPromiseRejectionWarning: ReferenceError: latest_provinces_confirmed is not defined

How can I get the result of the CSVtoJSON into a variable to use later

Thanks in advance

nad34
  • 343
  • 4
  • 13

2 Answers2

0

You are doing a simple and a beginner level mistake. The scope of "let" is only inside the block. Change your code as below and it should work.

(async() => {
    let latest_provinces_confirmed;
    csvToJson().fromStream(request.get("https://raw.githubusercontent.com/dsfsi/covid19za/master/data/covid19za_provincial_cumulative_timeline_confirmed.csv"))
    .then(source => {
         latest_provinces_confirmed = source;
         console.log(latest_provinces_confirmed)
         ....        
    });
Sreehari
  • 1,328
  • 11
  • 29
  • Thank you, but unfortunately it does not solve my problem as I would like to access `latest_provinces_confirmed` later in my code not just within the csv to json function – nad34 May 23 '20 at 10:45
0

The variable 'lastest_provinces_confirmed' is declared inside the anonymous function so you cannot access it outside that function. Thats why console.logging variable doesn't work.

You can try to pass that variable outside of that function by returning it OR you can forward declare that variable outside those functions to be able to access it.

Something like this might work:

let latest_provinces_confirmed = csvToJson().fromStream(request.get("https://raw.githubusercontent.com/dsfsi/covid19za/master/data/covid19za_provincial_cumulative_timeline_confirmed.csv"))
.then(source => {

  return source;
});

Remember to take account that you are working with async functions so you have to make sure that function csvToJson() has run before using 'latest_provinces_confirmed'. You can check use of "await" in order to do that!

tinokaartovuori
  • 698
  • 4
  • 5