我正在尝试学习异步等待。我有下面的代码,但由于某种原因我得到错误"Cannot convert undefined or null to object" on the line:let objArray = Object.entries(dividendFile['Monthly Adjusted Time Series']). 我想这是因为承诺.all在:const apiData = await Promise.all([fetchPrice, fetchDividend])** 不等了吗?我知道api调用本身并没有错,当我单独尝试时它工作正常,所以问题是我用异步等待做错了什么。任何想法可能是什么问题?我认为问题在于: //API 1 const urlData1 = { url: 'https://www.alphavantage.co/query?function=', theFunction: 'TIME_SERIES_DAILY', symbol: tickerSymbol, apiKey: key, outputsize: 'compact' }; const {url,theFunction,symbol,apiKey, outputsize} = urlData1 const apiUrl1 = `${url}${theFunction}&symbol=${symbol}&outputsize=${outputsize}&apikey=${apiKey}`; const fetchPrice = fetch(apiUrl1) //API 2 const urlData2 = { url2: 'https://www.alphavantage.co/query?function=', theFunction2: 'TIME_SERIES_MONTHLY_ADJUSTED', symbol2: tickerSymbol, apiKey2: key }; const {url2,theFunction2,symbol2,apiKey2} = urlData2 const apiUrl2 = `${url2}${theFunction2}&symbol=${symbol2}&apikey=${apiKey2}`; const fetchDividend = fetch(apiUrl2) const apiData = await Promise.all([fetchPrice, fetchDividend]); //<--- Seems to be a problem here const priceFile = await apiData[0].json const dividendFile = await apiData[1].json //Get data from API 1 let getPrice = new Promise(resolve => { let priceArray = Object.entries(priceFile['Time Series (Daily)']) //<--- "Error: Cannot convert undefined or null to object" let price = parseFloat(priceArray['0']['1']['4. close']); console.log('price: '+ price) resolve(price) })
1 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
是的。。。调试器帮助...我从未见过Promise.all()未能做到它应该做的事情。在调试器中,您很快就会看到您的json仅包含比您预期的要少的东西 - 一个函数,而不是此函数返回的承诺。
试试吧
const [priceFile, dividentFile] = await Promise.all([
fetchPrice.then(result => result.json()),
fetchDividend.then(result => result.json())
])
通过这种方式,您不仅可以并行化抓取,还可以并行化正文解析,尽管如果您只是将一些常见代码提取到函数中,而不是实质上复制粘贴2个请求的相同代码,则可以将其转换为更好的实现。
添加回答
举报
0/150
提交
取消