I am loading data from a csv file with d3.csv(). I am trying to call a named function after returning the data, but this does not seem to work. It gives me the following error:
Uncaught ReferenceError: Cannot access 'driving' before initialization
let driving = d3.csv("./driving.csv").then( ConnectedScatterplot(driving, {
x: d => d.miles,
y: d => d.gas,
title: d => d.year,
orient: d => d.side,
yFormat: ".2f",
xLabel: "Miles driven (per capita per year) →",
yLabel: "↑ Price of gas (per gallon, adjusted average $)",
width:600,
height: 720,
duration: 5000 // for the intro animation; 0 to disable
})) ;
if I do the following:
let driving = d3.csv("./driving.csv").then(function (driving) { ConnectedScatterplot(driving, {
It doesn't error and has 'driving' available, but it also doesn't do what I want, which is call ConnectedScatterplot with the parameters.
It seems d3.csv()
returns a Promise, then we have 2 ways to handle the result of the csv function:
As you did, just call ConnectedScatterplot
in then block:
d3.csv("./driving.csv").then((driving) => { // let driving is redundant
ConnectedScatterplot(driving, {...});
})
If you are inside an async function, you can use await
syntax:
(async () => { // async function
const driving = await d3.csv("./driving.csv"); // await
ConnectedScatterplot(driving, {...});
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.