我正在嘗試學習異步等待。我有下面的代碼,但由于某種原因我得到錯誤"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) })
承諾.一切都不等了嗎?
蕭十郎
2022-08-18 10:34:50