青春有我
2023-08-18 10:16:27
我目前正在學(xué)習(xí) JavaScript,并一直在使用 API(本例中為雅虎財(cái)經(jīng))。目標(biāo)是使用特定股票的財(cái)務(wù)數(shù)據(jù)更新價(jià)值表 - 但我需要在更新數(shù)據(jù)之前獲取數(shù)據(jù)。我以為我可以使用所示的等待/異步,但它不起作用。有什么指點(diǎn)嗎?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_花開(kāi)花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
您主要有兩個(gè)選擇:將代碼保留為現(xiàn)在的樣子,但使用它來(lái)等待運(yùn)行updateStockTabel:
request().then(() => updateStockTabel());
或者將您更改getStockStatistics為異步函數(shù)以執(zhí)行非常相似的操作,但使用 async/await 語(yǔ)法:
async function getStockStatistics(){
//Get symbol from input field
inputSymbol = document.getElementById("inputSymbol").value;
console.log(inputSymbol);
await request();
updateStockTabel();
}
添加回答
舉報(bào)
0/150
提交
取消