简化:
使用Axios获取数据
使用返回数组将数据放入数组和end函数中
数组被传递给函数。
来自数组的控制台日志数据
它为什么返回未定义的?
长篇故事:
我对单一责任原则重新编码,因此函数调用并返回天气数据,然后创建一个函数,将数据作为元素添加到hmtlDom中。
我需要能够从API数据中选择特定的变量,我只是在学习JSON,我确信我做错了,所以我简化了结果,我使用的是类型记录,所以这可能是一个类型问题。阅读文档没有帮助,最后的度假村在这里。
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)
// }
}控制台返回:未定义的
发布于 2020-09-25 14:18:10
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)
}
}https://stackoverflow.com/questions/64065046
复制相似问题