我正在尝试运行一个异步函数,该函数会在html脚本中生成chart.js图表,但没有任何显示。当我将代码更改为与虚拟数据同步时,它可以工作。
带有图表位置的html画布:
<div class="tile is-4 is-parent">
<div class="tile is-child box">
<canvas id="myChart"></canvas>
</div>
</div>
html脚本:
<script type="text/javascript" src="profile.js"></script>
<script type="text/javascript">
makeBTCWeeklyLineChart()
</script>
profile.js:
const axios = require('axios')
const config = require(path.resolve(__dirname, "./config.js"))
const moment = require('moment')
const json = require("json")
async function makeBTCWeeklyLineChart() {
let chrt = document.getElementById("myChart").getContext("2d")
let obj = await getBTCweekly()
let data = {
labels: obj.labels,
datasets: [
{
label: "Weekly Market Cap",
backgroundColor: "#0B244399",
borderColor: "#0B244399",
hoverBackgroundColor: "#0B244399",
hoverBorderColor: "#0B244399",
data: obj.data
}
]
}
let myFirstChart = new Chart(chrt, {
type: "line",
data: data,
options: {
responsive: true,
title: {
display: true,
text: 'BTC Weekly Market Cap'
},
scales: {
xAxes: [{
type: "time",
time: {
format: 'YYYY-MM-DD',
}
}]
}
}
})
}
async function getBTCweekly(){
let response = await axios.get('https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_WEEKLY&symbol=BTC&market=USD&apikey=' + config.apikey)
let obj = { labels: [], data: [] }
const data = response.data['Time Series (Digital Currency Weekly)']
for(let key in data){
obj.labels.push(key)
if (data.hasOwnProperty(key)){
obj.data.push(parseFloat(data[key]['6. market cap (USD)']))
}
}
return obj
}
我已经尽力想了一切。对我来说,似乎页面在脚本没有时间完成之前就已加载,但是我在其他地方读到,脚本应该在html完成解析之前运行完成。极少有可能是json格式问题,但我不认为任何图表输入均不正确。我真的很茫然。