异步函数返回值为空,传入另一函数调用时报split属性读取错误
问题原因分析
- 异步函数未加
await等待执行结果:read_fortune_500是异步函数,直接调用返回的是Pending状态的Promise对象,不是你预期的股票代码值,你把Promise对象传入yahooStockPrices.getCurrentData方法,该方法内部尝试对入参调用split方法,自然会报无法读取undefined属性的错误。 - 变量赋值逻辑错误:你初始化
stockSymbol为数组,但循环获取股票代码时直接用stockSymbol = tdValue赋值,每次循环都会覆盖之前的取值,最终只能拿到最后一只股票的代码,不是你预期的前10只股票代码数组。 - 变量命名冲突:全局变量
stockSymbol和collect_stocks的入参名完全一致,极易出现作用域混乱的问题。
修复后的代码
// 移除全局变量,改用函数返回值传递数据 async function read_fortune_500() { const stockSymbol = []; // 改为函数内部变量避免作用域污染 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().trim() if (tdValue) { stockSymbol.push(tdValue) // 用push方法添加到数组,不要直接覆盖变量 } }) console.log(stockSymbol[parentIndex]) } }) } catch (err) { console.error(err) } return stockSymbol; } async function collect_stocks() { const stockSymbol = await read_fortune_500() // 加await等待异步函数执行完成拿到返回值 const stockResult = await yahooStockPrices.getCurrentData(stockSymbol); console.log(stockResult); } collect_stocks()
验证说明
你之前单独运行read_fortune_500能正常输出,是因为打印的时机是在异步请求完成后的循环里,而之前collect_stocks调用时没有等待异步执行完成,所以拿到的是空值/Promise对象。修复后调用collect_stocks即可正常拿到股票数据。
内容的提问来源于stack exchange,提问作者Dave Michaels
相关产品推荐
相关产品推荐

