簡體   English   中英

如何使用從另一個 API 獲取的數據獲取數據?

[英]How to fetch from one API using data fetched from another?

我正在嘗試使用short_namestock_data state 變量中每只股票的價格。 這是我的useEffect function,它為我完成了所有的提取工作。 fetch_BSE_Data將存儲在stock_data中。 但是我使用的 API 沒有給出任何股票的價格細節。 因此,我嘗試在fetch_price_data function 中使用 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中的dataundefined數組的形式出現。 我究竟做錯了什么?

您需要使用Promise.all以便並行獲取所有價格:


// Since fetch_BSE_Data and fetch_price_data are doing the 
// same thing (fetching data), you can make a generic function 
// for fetching that takes a url as an argument.

const fetchData = async (url) => {
  try {
    const response = await fetch(url)
    if (!response.ok) throw response.statusText
    const data = response.json()
    return data
  } catch(error) {
    console.error(error)
  }
};

const getStockPrices = async () => {
  // Use the generic fetchData to get the list of stocks
  const stocks = await fetchData("https://api.bseindia.com/BseIndiaAPI/api/DefaultData/w?Fdate=20220912&Purposecode=P9&TDate=20221216&ddlcategorys=E&ddlindustrys=&scripcode=&segment=0&strSearch=S");

  // RegEx is a clean way to trim and remove any 
  // special characters or numbers from the shortNames
  const shortNames = stocks.map((stock) => stock.short_name.replace(/[^a-zA-Z]/g, ''));

  // Use the generic fetchData to get the stock
  // details for each of the shortNames and use
  // Promise.all to await the results of all of the data
  const prices = await Promise.all(shortNames.map((stock) => fetchData(`https://query1.finance.yahoo.com/v8/finance/chart/${stock}.BO`)))

  // Do other stuff to data...
}
   
getStockPrices()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM