callback function returning undefined

552 Views Asked by At

I'm trying to return an object inside a callback function

In the following situation, the console.log() show the result as expected

var dVizModule = (function(){
    let dataset;

    function loadData(fileName) {
        dataset = d3.csv(fileName, (data) => {
            dataset = data;
            console.log(dataset);
        });
    };

    return {
        loadData: loadData
    }

})();

dVizModule.loadData("data/time_scale_data.csv")

but when I try to use return in callback function the story is different and it returns undefined

var dVizModule = (function(){
    let dataset;

    function loadData(fileName) {
        dataset = d3.csv(fileName, (data) => {
            dataset = data;
            return dataset;
        });
        // return dataset; or even here!
    };

    return {
        loadData: loadData
    }

})();

console.log(dVizModule.loadData("data/time_scale_data.csv"))
1

There are 1 best solutions below

1
diwakersurya On

Since its a callback based workflow, the code above won't work. d3.csv is an asynchronous function, you can only get the result through a callback passed to it and hence even loadData needs to follow the same pattern.You just need to write something like this.

var dVizModule = (function(){
    function loadData(fileName,callback) {
        d3.csv(fileName, (data) => {
            callback(data);
        });
    };
    return {
        loadData: loadData
    }

})();

dVizModule.loadData("data/time_scale_data.csv",(data)=>{
  console.log(data);
})