javascript 如何从 D3 v5 中的 CSV 文件加载数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49599691/
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
How to load data from a CSV file in D3 v5
提问by StormPooper
I'm trying to load data from a CSV file in D3; I have this code:
我正在尝试从 D3 中的 CSV 文件加载数据;我有这个代码:
function update (error, data) {
if (error !== null) {
alert ("Couldn't load the dataset!");
} else {
//do something
};
function changeData () {
d3.csv ("data/dataset.csv", update);
}
If I use D3 v4 it works fine, but if I switch to v5 it doesn't work anymore. Can someone explain to me how to modify the code to make it work with D3 v5?
如果我使用 D3 v4 它工作正常,但如果我切换到 v5 它不再工作。有人可以向我解释如何修改代码以使其与 D3 v5 一起使用吗?
回答by pmkro
d3 v5uses the fetch API and returns a promise requiring the below code.
d3 v5使用 fetch API 并返回一个需要以下代码的承诺。
d3.csv('yourcsv.csv')
.then(function(data) {
// data is now whole data set
// draw chart in here!
})
.catch(function(error){
// handle error
})
In case in the future people want v4. d3 v4on the other hand uses the XMLHttpRequest method, and does not return a promise requiring this code
以防将来人们想要 v4。另一方面,d3 v4使用 XMLHttpRequest 方法,并且不返回需要此代码的承诺
d3.csv('yourcsv.csv', function(data) {
//whole data set
// draw chart here
})
csv loading is async so make sure to run your chart code within the csv function.
csv 加载是异步的,因此请确保在 csv 函数中运行您的图表代码。
回答by humfuzz
@pmkro's answeris good, but if you want to use ES7 async/awaitinstead of Promise.then:
@pmkro 的回答很好,但是如果您想使用 ES7 async/ await而不是 Promise.then:
async function doThings() {
const data = await d3.csv('yourcsv.csv');
// do whatever with data here
}
doThings();

