我目前正在学习 JavaScript,并一直在使用 API(本例中为雅虎财经)。目标是使用特定股票的财务数据更新价值表 - 但我需要在更新数据之前获取数据。我以为我可以使用所示的等待/异步,但它不起作用。有什么指点吗?let stats;let inputSymbol;let stockName;let stockSymbol;let stockPrevClose;let stockOpen;let stockMarketCap;let stockDayHigh;function getStockStatistics(){ //Get symbol from input field inputSymbol = document.getElementById("inputSymbol").value; console.log(inputSymbol); request(); updateStockTabel();}//Fetch data from Yahoo Finance API based on variablesconst request = async () => { const response = await fetch(`https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/get-financials?symbol=${inputSymbol}®ion=US`, { "method": "GET", "headers": { "x-rapidapi-key": "---", "x-rapidapi-host": "---" } }); const data = await response.json(); stats = data; console.log(data);}//Update statistics in table based on values from Yahoo Finance JSON objectfunction updateStockTabel() { //Change properties stockPrevClose = stats.summaryDetail.previousClose.raw; stockOpen = stats.summaryDetail.open.raw; stockMarketCap = stats.summaryDetail.marketCap.fmt; stockDayHigh = stats.price.regularMarketDayHigh.fmt; stockName = stats.price.longName; stockSymbol = stats.meta.symbol; //Connect document properties with variables document.getElementById("stocPrevClose").innerText = stockPrevClose; document.getElementById("stockOpen").innerText = stockOpen document.getElementById("stockMarketCap").innerText = stockMarketCap; document.getElementById("dayHigh").innerText = stockDayHigh; document.getElementById("stockName").innerText = stockName; document.getElementById("stockSymbolOutput").innerText = stockSymbol;}
1 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
您主要有两个选择:将代码保留为现在的样子,但使用它来等待运行updateStockTabel:
request().then(() => updateStockTabel());
或者将您更改getStockStatistics为异步函数以执行非常相似的操作,但使用 async/await 语法:
async function getStockStatistics(){
//Get symbol from input field
inputSymbol = document.getElementById("inputSymbol").value;
console.log(inputSymbol);
await request();
updateStockTabel();
}
添加回答
举报
0/150
提交
取消