【问题标题】:Returned values in asynchronous functions are empty异步函数中的返回值为空
【发布时间】:2022-01-11 23:35:56
【问题描述】:

我看到有其他与此主题相关的帖子,但我似乎无法找到对我的情况有所帮助的解决方案。我有两个异步函数。一个是返回要在另一个函数中使用的值。由于某种原因,正在使用的值被作为空变量读入。我不知道还有什么方法可以完成这项工作,但任何观点都会受到赞赏。

代码

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)

错误

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

如果我运行第一个函数,我能够将值记录到控制台,所以我知道值在那里,但我不确定将它传递给第二个函数的错误在哪里。

【问题讨论】:

  • stockSymbol = read_fortune_500()

标签: javascript node.js asynchronous async-await


【解决方案1】:

您将read_fortune_500 定义为异步函数,因此它返回一个promise。您可能打算在collect_stocksawait

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

【讨论】:

    猜你喜欢
    • 2022-06-27
    • 2021-10-02
    • 2013-09-27
    • 2022-01-14
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多