2

I'm using PapaParse to download CSV files from my JavaScript scripts and it's working great.

However, I've got a page where I need to download two files and only then do some work, and I was wondering if there was a neater way to do this than this:

Papa.parse(url_seriesy, {
    download: true,
    header: true,
    keepEmptyRows: false,
    skipEmptyLines: true,
    error: function(err, file, inputElem, reason) { // handle },
    complete: function(y_results) {
            Papa.parse(url_seriesx, {
                download: true,
                header: true,
                keepEmptyRows: false,
                skipEmptyLines: true,
                error: function(err, file, inputElem, reason) { // handle },
                complete: function(x_results) {
                    console.log(x_results.data);
                }
            });
    }
});

This works, but is pretty unwieldy. Is there anything else I can do? Perhaps I could use promises?

Richard
  • 62,943
  • 126
  • 334
  • 542

1 Answers1

4

If I understand correctly, you want to parse each file and then do something once all the results are collected. There are a few ways to do it but this is one way I might do it (Note: I haven't run this code; it probably needs tweaking):

var files = ["file1.csv", "file2.csv"];
var allResults = [];

for (var i = 0; i < files.length; i++)
{
    Papa.parse(files[i], {
        download: true,
        header: true,
        skipEmptyLines: true,
        error: function(err, file, inputElem, reason) { /* handle*/ },
        complete: function(results) {
            allResults.push(results);
            if (allResults.length == files.length)
            {
                // Do whatever you need to do
            }
        }
    });
}
Matt
  • 22,721
  • 17
  • 71
  • 112
  • This is a reasonable answer. I might promote to maintaining an array of promises over an array of results, but the end result should be the same. – Tony Apr 02 '15 at 19:11
  • 1
    Fair enough. Also note I got rid of the keepEmptyRows option, that went away in version 4. – Matt Apr 02 '15 at 20:14
  • You may also want `allResults` to be an object and not a list, for having access to the 2 datases. E.g., `{file1.csv: {…}, file2.csv: {…}}` (I think that could avoid problems with asynchronicity. I don't know if there are smarter alternatives...) – floatingpurr Mar 28 '18 at 10:02