Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returned values in asynchronous functions are empty

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%26P_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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading