我尝试使用short_name
键获取stock_data
状态变量中的每只股票的价格。下面是我的useEffect
函数,它为我完成了所有的获取工作。fetch_BSE_Data
将存储在stock_data
中。但是我用于它的API并没有给予股票的任何价格细节。因此,我尝试在fetch_price_data
函数中使用Yahoo的API获取价格:
正在获取UseEffect
useEffect(() => {
const fetch_BSE_Data = async () => {
console.log("fetching data");
return await fetch(
"https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S"
)
.then((response) => response.json())
};
const fetch_price_data = async () => {
const data = stock_data.map((stock) => {
var shortName = stock.short_name;
if (stock.short_name.includes(" ")) {
shortName = stock.short_name.replace(" ", "")
}
else if (stock.short_name.includes("*")) {
shortName = stock.short_name.replace("*", "")
}
fetch(`https://query1.finance.yahoo.com/v8/finance/chart/${shortName}.BO`)
.then((response) => response.json())
.then((response) => {
if (response.chart.result[0]) {
console.log("result: ", response.chart.result, "response: ", response.chart.result[0].meta.previousClose)
return response.chart.result[0].meta.previousClose;
}
else {
console.log("ERROR:", response.chart.error.code);
return null;
}
});
})
return data
}
const fetchData = async () => {
const stock_response = await fetch_BSE_Data();
const price_data = await fetch_price_data();
console.log("price_data: ", price_data)
const mappedItems = makeMyNewData(stock_response, price_data);
setStockData(mappedItems);
console.log("stock_data after setStockData", stock_data);
}
fetchData();
}, []);
fetch_price_data
中的data
是undefined
的数组。我做错了什么?
1条答案
按热度按时间8qgya5xd1#
您需要使用
Promise.all
,以便并行获取所有价格: