拉莫斯之舞
您的假设是正确的,问题与异步方法有关fetch()方法。无需在window.onload中创建图表。一旦获取的数据以图表配置中使用的格式可用,就应该创建它们。因此,正确的位置是在最后一个 fetch(...).then() 的末尾。fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv') .then(response => { return response.text(); }) .then((data) => { ... chartItCTCases(cases, days); chartItCTDeaths(deaths, days); })请查看下面您修改后的代码。window.onload = function() { getData('New York');}function chartItCTCases(cases, days) { var ctx = document.getElementById('CoronaChartCTCases').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ label: 'Cases', data: cases, backgroundColor: "rgb(207,181,59)" }] }, options: { title: { display: true, text: 'Total CoronaVirus Cases in the State' }, maintainAspectRatio: false, responsive: true, scales: { xAxes: [{ ticks: { autoSkip: true, maxTicksLimit: 12 }, display: true, scaleLabel: { display: true, labelString: 'Days since first case in the State' }, }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Total Cases in the state' } }] } } });}function chartItCTDeaths(deaths, days) { var ctx = document.getElementById('CoronaChartCTDeaths').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: days, datasets: [{ label: 'Deaths', data: deaths, backgroundColor: "rgb(207,181,59)" }] }, options: { title: { display: true, text: 'Total CoronaVirus Deaths in the State' }, responsive: true, maintainAspectRatio: false, scales: { xAxes: [{ ticks: { autoSkip: true, maxTicksLimit: 12 }, display: true, scaleLabel: { display: true, labelString: 'Days since first case in the State' }, }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: 'Total Deaths in the state' } }] } } });}function getData(state) { cases = []; deaths = []; days = []; fetch('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv') .then(response => { return response.text(); }) .then((data) => { const table = data.split('\n').slice(1); curDay = 0; table.forEach((row) => { const columns = row.split(','); if (columns[1] == state) { cases.push(columns[3]); deaths.push(columns[4]); days.push(curDay++); } }); chartItCTCases(cases, days); chartItCTDeaths(deaths, days); })}<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script><div class="col-xs-12"> <div style="height: 300px; width: 45%;display:inline-block;"> <canvas id="CoronaChartCTCases"> </canvas> </div> <div style="height: 300px; width: 45%;display:inline-block;"> <canvas id="CoronaChartCTDeaths"></canvas> </div></div>