Download multiple files using PapaParse?

梦想的初衷 提交于 2019-12-08 02:56:37

问题


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


来源:https://stackoverflow.com/questions/29410435/download-multiple-files-using-papaparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!