16

I'm sort of embarrassed to ask this question because it seems like it should be so obvious, but I'm pretty weak on dealing with async problems, and I'm confused on how to proceed.

I'm using Papa Parse (http://papaparse.com/docs.html#remote-files) to parse a remote CSV. I want to stash the result of the parse in an object to use later. Here's my code:

var dataset = {};    

    Papa.parse("http://path/to/some.csv", {
      download: true,
      dynamicTyping: true,
      complete: function(results) {
        dataset = results.data;
      }
    });

console.log(dataset);  

This, of course, results in an empty object being logged to the console. Any attempts at using dataset don't work because, of course, the dataset object hasn't actually received its data by the time the code executes. Can someone please help me refactor or explain how I deal with this?

TheNovice
  • 1,277
  • 3
  • 16
  • 23

1 Answers1

30

Is there a reason the dataset variable needs to be used outside of the function? The easiest way to ensure that the dataset is populated is to manipulate the dataset in the 'complete' function right after it is, well, populated.

An alternative is to add a callback like so:

function doStuff(data) {
    //Data is usable here
    console.log(data);
}

function parseData(url, callBack) {
    Papa.parse(url, {
        download: true,
        dynamicTyping: true,
        complete: function(results) {
            callBack(results.data);
        }
    });
}

parseData("tests/sample.csv", doStuff);
colonelsanders
  • 824
  • 6
  • 19
  • 1
    This was exactly the reorientation I needed. I'm still learning about callbacks and async, so this really helped demystify it for me. THANK YOU!!!! – TheNovice Oct 08 '14 at 23:42
  • Yup! Worked like a charm adding in the callback! Thank you! – WizzyBoom Jul 21 '15 at 03:36
  • for some reason, I can't seem to get this to work. Can someone help me at https://stackoverflow.com/questions/51013182/how-to-get-papa-parse-results-into-an-array – swv Jun 24 '18 at 21:31
  • @colonelsanders I couldn't get my head around that problem, and then I found your answer. It solved everything ! Thank you so much ! – JrmDel Apr 01 '20 at 16:13