嘿,我可能会在其他地方回答这个问题,但找不到适合我需求的答案。这段代码:
async function makeCharts(coin){
let results = await Promise.all([getDailyData(coin), getCurrentData(coin)])
makeCurrentLineChart(coin, results[1])
makeHighLowLineChart(coin, results[0])
}
似乎并不等待结果数组被解析。两种图表方法有时不传递任何数据,有时效果很好。
这些是异步功能:
async function getDailyData(coin){
let response = {}
try{
response = await axios.get('https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_DAILY&symbol='+ coin +'&market=USD&apikey=' + APIKEY)
}catch(err){
response = err
}
let obj = { labels: [], highdata: [], lowdata: [] }
const data = response.data['Time Series (Digital Currency Daily)']
let i = 0
for(let key in data){
if(i == 21) break;
i = i+1
obj.labels.push(key)
if (data.hasOwnProperty(key)){
obj.highdata.push(parseFloat(data[key]['2a. high (USD)']))
obj.lowdata.push(parseFloat(data[key]['3a. low (USD)']))
}
}
return obj
}
async function getCurrentData(coin){
let response = {}
try{
response = await axios.get('https://www.alphavantage.co/query?function=DIGITAL_CURRENCY_INTRADAY&symbol='+ coin +'&market=USD&apikey=' + APIKEY)
}catch(err){
response = err
}
let obj = { labels: [], currentdata: [] }
const data = response.data['Time Series (Digital Currency Intraday)']
let i = 0
for(let key in data){
if(i == 100) break;
i = i+1
obj.labels.push(key.split(' ')[1])
if (data.hasOwnProperty(key)){
obj.currentdata.push(parseFloat(data[key]['1a. price (USD)']))
}
}
return obj
}
我看过丹尼尔·希夫曼(Daniel Shiffman)的诺言视频,这似乎与那里的逻辑相符:
https://www.youtube.com/watch?v=01RTj1MWec0&t=57s
我也在这里查看,并且makeCharts函数与“摘要”部分上方的语法相匹配: