在 Javascript 对象中从 CSV 中检索解析的数据(使用 Papa Parse)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26266459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:44:37  来源:igfitidea点击:

Retrieve parsed data from CSV in Javascript object (using Papa Parse)

javascriptparsingcsvasynchronouscallback

提问by TheNovice

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:

我正在使用 Papa Parse ( http://papaparse.com/docs.html#remote-files) 来解析远程 CSV。我想将解析结果存储在一个对象中以备后用。这是我的代码:

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?

当然,这会导致一个空对象被记录到控制台。任何使用数据集的尝试都不起作用,因为当然,数据集对象在代码执行时实际上还没有收到它的数据。有人可以帮我重构或解释我如何处理这个问题吗?

回答by colonelsanders

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