whytheq
whytheq

Reputation: 35577

Move this js to a function

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

Upvotes: 0

Views: 42

Answers (1)

baao
baao

Reputation: 73251

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.

Upvotes: 2

Related Questions