1

I just have a csv file and I'm trying to get the data with an async function but I'm getting undefined.

<script>
    async function data(pathToCsv) {
        return await d3.csv(pathToCsv, function (data) {
            data.year = +data.year
            data.running_total = +data.running_total
            data.date = new Date(data.year, 0)
            return data
        })
    };
    let dataset = data('q3.csv');
    console.log(dataset.year);
</script>
Ramin Melikov
  • 967
  • 8
  • 14
  • Take a look at this post https://stackoverflow.com/questions/19899005/d3-make-the-d3-csv-function-syncronous – Guillermo Sep 14 '20 at 09:54

2 Answers2

2

The issue here is that your data function is returning a promise, and so accessing year from a promise object will return undefined, you need to add await when calling your data function

 async function data(pathToCsv) {
        return await d3.csv(pathToCsv, function (data) {
            data.year = +data.year
            data.running_total = +data.running_total
            data.date = new Date(data.year, 0)
            return data
        })
   };

  async function init() {
     let dataset = await data('q3.csv');
     // this should work now assuming you are using d3 function correctly as i'm not aware of d3 functions myself
     console.log(dataset.year); 
  }

  init()
ehab
  • 7,162
  • 1
  • 25
  • 30
  • Getting undefined still – Ramin Melikov Sep 14 '20 at 10:22
  • @RaminMelikov then either csv does return a promise that resolves to undefined, or the data you are accessing is not correct, anyway after a quick search it seems for me the csv function does return an array, and so u might wanna try dataset[0].year. Either case sart with console.log(dataset) and see what happens. I can help you more if u setup a reproducible example using codesandbox or something similar – ehab Sep 14 '20 at 10:43
0

I solved it.

<script>

    async function data(pathToCsv) {
        let dataset = await d3.csv(pathToCsv, function (d) {
            d.year = +d.year
            d.running_total = +d.running_total
            d.date = new Date(d.year, 0)
            return d
        })
        return dataset
    };

    data('q3.csv').then(function(d) {
        d.forEach(function(p){
            console.log(p.date.getFullYear());
        })
    });

</script>
Ramin Melikov
  • 967
  • 8
  • 14