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

时间:2020-12-05 01:38:56

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?

当然,这会导致将空对象记录到控制台。任何使用数据集的尝试都不起作用,因为当然,数据集对象在代码执行时并未实际接收到其数据。有人可以帮我重构或解释我是如何处理的吗?

1 个解决方案

#1


22  

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

#1


22  

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