I'm trying to fetch a json file the api in the code below ,When I convert the json response to a javascript object I expect to be able to access the value of the key results
in that object which is an array but when i log the response in the second then chain i get unidentified
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000"
fetch(URLS)
.then(response => {
return response.json().results
})
.then((pokemons) => {
console.log(typeof pokemons)
});
When I changed the code to this
const URLS = "https://pokeapi.co/api/v2/pokemon?limit=1000"
fetch(URLS)
.then(response => {
return response.json()
})
.then((pokemons) => {
console.log(typeof pokemons.results)
});
it seems working fine but i don't understand why this problem is happening
CodePudding user response:
response.json()
returns a Promise
resolving to the result of parsing the text of the response as JSON. You cannot directly access properties on that result without awaiting the Promise with .then
or await
in an async
function.