【发布时间】: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