You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JavaScript调用pokeapi异步拉取数据后无法访问对象属性怎么办

问题原因

核心是异步操作执行时序错误:getPokemonAxios是async异步函数,调用后会立即返回Promise,不会阻塞后续代码执行,你写的console.log(pokemonarray)执行时,接口请求还没完成,数组还是空的,自然拿不到属性值。你在控制台看到的是数组填充后的快照,和代码执行时的实时值不一致。

正确实现代码

方案1:在异步函数内部完成打印/操作

let pokemonarray = []
const getPokemonAxios = async () => {
  for (let i = 1; i <= 5 ; i++) {
    try {
      const res = await axios(`https://pokeapi.co/api/v2/pokemon/${i}`);
      pokemonarray.push(res.data) // 不需要额外解构,直接存返回数据即可
    } catch (error) {
      console.log(error)
    }
  }
  // 所有请求完成后再操作数组
  pokemonarray.forEach(item => {
    console.log('宝可梦名称:', item.name)
    // types是数组结构,需要遍历取出每个属性的名称
    console.log('宝可梦属性:', item.types.map(t => t.type.name))
  })
}

getPokemonAxios()

方案2:等待异步函数执行完成后再操作

let pokemonarray = []
const getPokemonAxios = async () => {
  for (let i = 1; i <= 5 ; i++) {
    try {
      const res = await axios(`https://pokeapi.co/api/v2/pokemon/${i}`);
      pokemonarray.push(res.data)
    } catch (error) {
      console.log(error)
    }
  }
  return pokemonarray
}

// 用then接收异步执行完成的信号后再操作数组
getPokemonAxios().then(() => {
  console.log(pokemonarray[0].name)
})

// 如果是支持顶层await的环境(比如ES模块、浏览器控制台)也可以直接写:
// await getPokemonAxios()
// console.log(pokemonarray[0].name)

内容的提问来源于stack exchange,提问作者mrcode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:57:00