Home > other >  Returned values in asynchronous functions are empty
Returned values in asynchronous functions are empty

Time:12-07

I see there have been other posts related to this topic, but I can't seem to find a solution that helps my situation. I have two asynchronous functions. One is returning a value that is to be used in the other function. For some reason, the value being used is being read in as an empty variable. I don't know how else to make this work, but any perspective would be appreciated.

Code

var stockSymbol = [];
async function read_fortune_500() {
  try {
    const { data } = await axios({ method: "GET", url: "https://en.wikipedia.org/wiki/List_of_S&P_500_companies", })
    const $ = cheerio.load(data)
    const elemSelector = '#constituents > tbody > tr > td:nth-child(1)'

    $(elemSelector).each((parentIndex, parentElem) => {
      if (parentIndex <= 9){
      $(parentElem).children().each((childIndex, childElem) => {
        const tdValue = $(childElem).text()

        if (tdValue) {
          stockSymbol = tdValue
        }
      })
      console.log(stockSymbol)
    }
    })
} catch (err) {
    console.error(err)
  }
  return stockSymbol;
}

async function collect_stocks(stockSymbol) {
  stockSymbol = read_fortune_500()
  const stockResult = await yahooStockPrices.getCurrentData(stockSymbol);
  console.log(stockResult);
}

collect_stocks(stockSymbol)

Error

TypeError: Cannot read properties of undefined (reading 'split')

If I run the first function, I am able to get values logged to the console, so I know values are there, but I'm not sure where I'm going wrong passing it in to the second function.

CodePudding user response:

You defined read_fortune_500 as an async function, so it returns a promise. You probably meant to await it in collect_stocks.

async function collect_stocks(stockSymbol) {
  stockSymbol = await read_fortune_500()
  const stockResult = await yahooStockPrices.getCurrentData(stockSymbol);
  console.log(stockResult);
}
  • Related