如何正确解析JSON结果

问题描述 投票:0回答:2

我目前正在使用 PokeAPI,我正在执行获取请求以在给定端点接收 JSON,然后尝试解析并返回它。可以在这里找到执行此操作的函数:

function getPokemon(id){

    pokemonData = {
        name:"",
        image:"",
        id:id,
        description:""
    }
    
    // Documentation https://pokeapi.co/docs/v2#pokemon-species
    fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)
      .then((response) => response.json())
          .then((data) => {
        
            pokemonData.description = data.flavor_text_entries[0].flavor_text.toString()
            
          }
        )
    
    // Documentation: https://pokeapi.co/docs/v2#pokemon
    fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
      .then((response) => response.json())
          .then((data) => {
        
            pokemonData["image"] = data.sprites.other["official-artwork"].front_default.toString()
            pokemonData["name"] = data.name.toString()
            
          }
        )

    return pokemonData
}

返回数据后,尝试访问属性为空,但对象显示正确的信息:

我不确定这里出了什么问题。我尝试了每种不同的属性访问格式

data.name
data["name"]
,但似乎没有什么区别。任何帮助将不胜感激

javascript fetch-api
2个回答
1
投票

您自己的答案在解决您的问题方面是正确的。
但它并没有充分利用

async / await
和承诺。

在两个

await
调用上使用
fetch
会使代码一一运行请求。您可以通过让两个
fetch
调用并行运行 并等待两者完成 Promise.all()
 来加快速度。

两个请求完成后,创建您的

pokemonData

 对象并根据两组数据返回它。

async function getPokemon(id) { const speciesRequest = fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`) .then((response) => response.json()) const pokemonRequest fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`) .then((response) => response.json()) try { const [speciesData, pokemonData] = await Promise.all([speciesRequest, pokemonRequest]); return ({ id, image: pokemonData.sprites.other["official-artwork"].front_default, name: pokemonData.name, description: speciesData.flavor_text_entries[0].flavor_text.toString() }); catch (error) { return Promise.reject(error); } }
    

0
投票
在写这篇文章的过程中,我明白了发生了什么。当使用

.then()

 时,我的理解是,这也等待响应并使其同步,因为在线资源声明了这一点。

这不是真的

我必须使我的函数成为异步函数,以便我可以等待提取,因为该函数的运行速度比提取发生的速度快。固定代码是:

async function getPokemon(id){ pokemonData = { name:"", image:"", id:id, description:"" } // Documentation https://pokeapi.co/docs/v2#pokemon-species await fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`) .then((response) => response.json()) .then((data) => { pokemonData.description = data.flavor_text_entries[0].flavor_text.toString() } ) // Documentation: https://pokeapi.co/docs/v2#pokemon await fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`) .then((response) => response.json()) .then((data) => { pokemonData.image = data.sprites.other["official-artwork"].front_default pokemonData.name = data.name console.log(data.name) } ) return pokemonData }
    
© www.soinside.com 2019 - 2024. All rights reserved.