P粉7399424052023-08-04 00:56:41
問題在於你宣告了一個名為historicalDividend的變量,並將其初始化為空數組,然後在每次迭代中重新分配整個變數給時間序列數據,這意味著你會覆蓋每次的值。此外,entry未定義,我認為你可能想使用date。
為了解決所有這些問題,你應該使用map()方法,它接受一個數組,循環遍歷它,並使用回調函數返回值創建一個新數組。
作為另一個提示:你應該檢查回應的HTTP狀態碼,以確保你獲得了預期的回應。
下面是修復了這兩個問題的你的程式碼版本:
async function fetchTimeSeriesDailyAdjusted(ticker) {
//Fetch function to get the daily close and the dividends
const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol
try {
const response = await fetch(apiTimeSeriesDailyAdjusted);
// Check for HTTP response code
if (!response.ok) {
throw new Error(
$`Fetching daily time series data failed with status code '${response.status}'`
);
}
const data = await response.json();
const historicalDividend = data["Time Series (Daily)"].map(
(entry) => entry["7. dividend amount"]
);
console.log(historicalDividend); //Console log to see the dividend
return historicalDividend; //Value that the function must return
} catch (error) {
console.error("Error fetching apiTimeSeriesDailyAdjusted"); //Log of the error
}
}