简体   繁体   English

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

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

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. 我正在使用Papa Parse( http://papaparse.com/docs.html#remote-files )来解析远程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? 有人可以帮我重构或解释我是如何处理的吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM