score:4

Accepted answer

When you run your code you should see that you are indeed loading the data. When I use your example data in a dsv/csv file and run your function I get the following logged to console:

enter image description here

So it appears as both your load of the dsv file is successful, and your row function is successful, based on the console log in the then method.

Let's take a closer look at the .then method, this runs after the file has loaded and the row function been applied - or, once the promise has been fulfilled. So the key part here is the then method doesn't execute the provided function until after the promise is fulfilled. While we are waiting for the the promise to be fulfilled, code continues to be executed, in your case the return statement executes - before the data is fully loaded and therefore before the then method executes. This means you aren't returning any data, and this is your problem.

The simplest and probably most common d3 patterns to fetch the data with your row function is to either place code that requires the loaded data in the .then method's fulfillment function:

function getCSVdata( ) {
    d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
        return {
            State : d.Country,
            freq: { 
                low  : d.Car,
                med  : d.Van,
                high : d.Truck
            }
        };
    }).then(function(data) {
      console.log("file has " + data.length + " rows");
      logger(data);
    }); 
}

getCSVdata();

function logger(data) {
	console.log(data);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://d3js.org/d3.v5.min.js"></script>

Or you could take a slightly different form:

function getCSVdata( ) {
    d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
        return {
            State : d.Country,
            freq: { 
                low  : d.Car,
                med  : d.Van,
                high : d.Truck
            }
        };
    }).then(fulfilled); 
}

getCSVdata();

function fulfilled(data) {
	// do stuff here:
    console.log(data);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://d3js.org/d3.v5.min.js"></script>


Related Query

More Query from same tag