1

With an array of Pokemon ids, I am hoping to get an array of Pokemon objects by fetching from the Pokemon API. The goal is to get from this

[1,2,3]

to this:

[
  {name: "ivysaur", weight: 130, …},
  {name: "venusaur", weight: 1000, …},
  {name: "bulbasaur", weight: 69, …}
]

I have taken a long hard look at this thread 'How can I fetch an array of urls with Promise.all' but none of the solutions are working for me. I have the same problem outlined in this answer, but the solution proposed still does not yield results.

My Promise.all is fulfilling with an array of undefineds, instead of the Pokemons. Why?

const pokemonIds = [1,2,3]

const pokemons = pokemonIds.map(id => {
 fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
   .then(res => res.json())
        .then(json => {
       console.log(json)
          return json
    })
})

Promise.all(pokemons).then(res => {
 console.log('pokemon arr: ', res)
})
Golo Roden
  • 140,679
  • 96
  • 298
  • 425
OctaviaLo
  • 1,268
  • 2
  • 21
  • 46

1 Answers1

2

You're missing return before fetch:

const pokemons = pokemonIds.map(id => {
    return fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
    .then(res => res.json())
        .then(json => {
          console.log(json)
          return json
    })
});

or:

const pokemons = pokemonIds.map(id => 
    fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
    .then(res => res.json())
        .then(json => {
          console.log(json)
          return json
    })
)
Phiter
  • 14,570
  • 14
  • 50
  • 84