-1

I am currently learning how to use JS promises, and specifically in this example, Promise.all to confirm an array of fulfilled promises before using .then() to pass this argument to a callback.

I have completed already a function and am not sure where this one is going wrong, When running the function in the browser it gets to print out our Pokemon promise array, with 3 fulfilled promises. It seems then anything after Promise.all is not running despite 3/3 fulfilled promises, what am I missing here?

function threePokes(){

  pokemonPromiseArray = [];
  
  let pokemon = axios.get('https://pokeapi.co/api/v2/pokemon?limit=10000')
    .then(pokeList => {
      console.log(pokeList)
    
      for(let i = 1; i <=3; i++){
        pokemonPromiseArray.push(axios.get(pokeList.data.results[i].url))
        console.log(pokeList.data.results[i].name)  
      }
      console.log(pokemonPromiseArray)
    }
  )
    
  Promise.all(pokemonPromiseArray)
    .then(pokeArr => pokeArr.forEach(element => {
      console.log(element)
      console.log("running?=")
  }))
}

threePokes()
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
vmank
  • 773
  • 2
  • 7
  • 22
  • 2
    `pokemonPromiseArray` is empty when `Promise.all()` is invoked, as the first `axios.get()` call hasn't completed at that time. The quick fix would be to put `Promise.all()` inside the first `get()` callback, directly after the `for` loop. – Rory McCrossan Aug 18 '23 at 07:59
  • I see, that makes sense, I believe I was hesitant to do that in order to avoid nested, but I suppose by using .then() after promise.all it would avoid that issue, thank you! – Sean.realitytester Aug 18 '23 at 08:01

0 Answers0