我看到還有其他與此主題相關的帖子,但我似乎找不到對我的情況有幫助的解決方案。我有兩個異步函式。一個是回傳要在另一個函式中使用的值。出于某種原因,正在使用的值被作為空變數讀入。我不知道如何才能使這項作業,但任何觀點將不勝感激。
代碼
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)
錯誤
TypeError: Cannot read properties of undefined (reading 'split')
如果我運行第一個函式,我可以將值記錄到控制臺,所以我知道值在那里,但是我不確定將它傳遞給第二個函式的地方出了什么問題。
uj5u.com熱心網友回復:
您定義read_fortune_500為異步函式,因此它回傳一個承諾。你可能打算await在collect_stocks.
async function collect_stocks(stockSymbol) {
stockSymbol = await read_fortune_500()
const stockResult = await yahooStockPrices.getCurrentData(stockSymbol);
console.log(stockResult);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/376061.html
標籤:javascript 节点.js 异步 异步等待
