1

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"))
zEn feeLo
  • 1,877
  • 4
  • 25
  • 45
  • `d3.csv` is an async function, and the `return dataset` statement is actually returning from the CB for `d3.csv()` function, and `loadData()` is not returning anything. – Mu-Majid Jan 20 '20 at 19:45
  • You can make `loadData` return a promise like this : ``` var dVizModule = (function(){ let dataset; function loadData(fileName) { return new Promise((resolve, reject) => { dataset = fs.readFile(fileName, (err,data) => { if (err) { reject(err) } dataset = data; resolve(dataset); }); }) }; return { loadData: loadData } })(); ``` – Mu-Majid Jan 20 '20 at 19:53

1 Answers1

0

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);
})
diwakersurya
  • 94
  • 1
  • 6
  • thats what exactly Im trying to avoid, passing a function to the API, is there any other solution ? because d3 is this way in the architecure, Im trying to build a API like version of it – zEn feeLo Jan 20 '20 at 19:25