0

我正在尝试将 CSV 从 CSV 文件转换为 JSON。

我有以下代码

(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)
...

当我运行它时,我得到 UnhandledPromiseRejectionWarning: ReferenceError: latest_provinces_confirmed is not defined

如何将 CSVtoJSON 的结果放入变量中以供以后使用

提前致谢

4

2 回答 2

0

您正在犯一个简单的初学者级别的错误。“let”的范围仅在块内。如下更改您的代码,它应该可以工作。

(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)
         ....        
    });
于 2020-05-23T10:39:38.457 回答
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!

于 2020-05-23T10:48:26.250 回答