阵列日志中的Axios数据未定义



简化:

使用Axios获取数据

将数据放入数组中,并使用返回数组结束函数

数组被传递给函数

来自阵列的控制台日志数据

为什么它返回undefined?


长话短说:

我正在重新编码到单一责任原则,因此函数调用并返回天气数据,稍后,创建一个函数,将数据作为元素添加到hmtlDom中。

我需要能够从API数据中选择特定的变量,我只是在学习JSON,我确信我做错了,所以我简化了结果,我在打字,所以可能是打字问题。阅读文档也无济于事,Last Resort就在这里。

export function getWeatherData(api : string) {

var weatherData: any = []

axios.get(api)
.then(function (response) {
weatherData.push(response.data.city.name)
})

.catch(function(error){
console.log(error)
})
return weatherData
}

在console.log(weatherData(中输入图像描述


function main() {
var city = getCity()
var api = getApi(city)
let weatherData = getWeatherData(api)
console.log(weatherData)
clearDivs()
addDivs(howManyReadings)
addDataToDivs(weatherData)
}

export function addDataToDivs(weatherData: any) {
// let li = document.getElementsByClassName("weatherInnerContainer")
// let nI = li.length
// for (var i = 0; i < nI; i++) {
console.log(weatherData[0])
// li[i].appendChild(weatherData['city']['name'])
// li[i].appendChild(weatherData['list'][i.toString()]['main']['temp'])
// li[i].appendChild(weatherData['list'][i.toString()]['dt_txt'])
// li[i].appendChild(weatherData['list'][i.toString()]['weather']['0']['description'])

// let nElement = document.createElement('img')
// let iconValue = (weatherData['list'][i.toString()]['weather']['0']['icon']).toString()
// let iconLink = 'https://openweathermap.org/img/wn/' + iconValue + '@2x.png'
// nElement.src = iconLink
// li[i].appendChild(nElement)

// }
}

控制台返回:未定义

axios.get是异步函数,它在"某个时间"发生,而您创建的函数是同步的。这意味着getWeatherData()的执行是立即的,并且它不等待axios.get的结果。

你可以通过承诺或回调来解决这个问题,无论你喜欢什么。基于承诺的解决方案看起来像这样:

export function getWeatherData(api : string) {
return axios.get(api)
.then(function (response) {
return response.data.city.name
})
.catch(function(error){
console.log(error)
})
}

function main() {
var city = getCity()
var api = getApi(city)
getWeatherData(api).then(weatherData => {
console.log(weatherData)
clearDivs()
addDivs(howManyReadings)
addDataToDivs(weatherData)
}
}

最新更新