Download multiple files using PapaParse?

2019-07-20 02:49发布

问题:

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?

回答1:

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