问题描述
我有点不好意思问这个问题,因为它看起来应该很明显,但我在处理异步问题方面非常薄弱,而且我对如何进行感到困惑.
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.
我正在使用 Papa Parse (http://papaparse.com/docs.html#remote-files) 解析远程 CSV.我想将解析结果存储在一个对象中以备后用.这是我的代码:
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:
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);
这篇关于在 Javascript 对象中从 CSV 中检索解析的数据(使用 Papa Parse)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!