0

I suspect this is very trivial but I have this code:

var latestMth;
d3.csv("data/blah.csv", function(rows) {
    x = rows.map(function(d) {
        return parseDate(d.dt)
    });
    latestMth = formatDateOutputMTH(d3.max(d3.values(x)));
});

...
...
.text("Month is " + latestMth);

It works ok displaying "Month is Mar17".

I've attempted to make the above a function but the result now comes through as "Month is undefined". Why is this happening:

var latestMth = function() {
    d3.csv("data/blah.csv", function(rows) {
        x = rows.map(function(d) {
            return parseDate(d.dt)
        });
        return formatDateOutputMTH(d3.max(d3.values(x)));
    });
}
...
...
.text("Month is " + latestMth());
whytheq
  • 34,466
  • 65
  • 172
  • 267

1 Answers1

2

Assuming d3.csv() is not async.

Because you don't return from your function:

var latestMth = function() {
    return d3.csv("data/blah.csv", function(rows) {  // added return 
        x = rows.map(function(d) {
            return parseDate(d.dt)
        });
        return formatDateOutputMTH(d3.max(d3.values(x)));
    });
}

Note, if it's async, you can use a Promise:

function setLatestMonth() {
    return new Promise((resolve, reject) => {
        d3.csv("data/blah.csv", function(rows) {
            x = rows.map(function(d) {
                return parseDate(d.dt)
            });
            resolve(formatDateOutputMTH(d3.max(d3.values(x))));
        });
    });
}

setLatestMonth().then(latestMonth => {
    // ...
    // ...
    // ...
    .text("Month is " + latestMonth);
});

I don't know d3.csv() - if it already returns a promise, you can simply chain that one instead of creating a new Promise by yourself.

baao
  • 71,625
  • 17
  • 143
  • 203
  • If it's async, check out this answer : http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call @whytheq – baao Mar 22 '17 at 09:31
  • @whytheq added a working version for async, but make sure to check what d3.csv() returns.. If it's a promise, chain that instead – baao Mar 22 '17 at 09:47
  • 1
    I'm using an old version of d3 so suspect that it won't be returning a promise - I'll try your code it looks very nice – whytheq Mar 22 '17 at 11:15