首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组日志中的Axios数据未定义

数组日志中的Axios数据未定义
EN

Stack Overflow用户
提问于 2020-09-25 13:24:17
回答 1查看 157关注 0票数 0

简化:

使用Axios获取数据

使用返回数组将数据放入数组和end函数中

数组被传递给函数。

来自数组的控制台日志数据

它为什么返回未定义的?

长篇故事:

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

我需要能够从API数据中选择特定的变量,我只是在学习JSON,我确信我做错了,所以我简化了结果,我使用的是类型记录,所以这可能是一个类型问题。阅读文档没有帮助,最后的度假村在这里。

代码语言:javascript
复制
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)

代码语言:javascript
复制
  function main() {
  var city = getCity()
  var api = getApi(city)
  let weatherData = getWeatherData(api)
  console.log(weatherData)

  clearDivs()
  addDivs(howManyReadings)
  addDataToDivs(weatherData)

}
代码语言:javascript
复制
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)
    
// }
}

控制台返回:未定义的

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-25 14:18:10

axios.get是异步函数,它发生在“一段时间”,而您创建的函数是同步的。这意味着,getWeatherData()的执行是立即的,它不会等待axios.get的结果。

您可以通过使用承诺或回调来解决这个问题,不管您喜欢什么。基于承诺的解决方案如下所示:

代码语言:javascript
复制
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)
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64065046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档