Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Order Pokémons from 1 to 20 not a random order

When I run this code it give me a random order of Pokémons. I don’t know where is the problem.

Thank you so much.

for (var i = 1; i <= 20; i++) {

    apiPokemon("https://pokeapi.co/api/v2/pokemon/"+i);

    async function apiPokemon(urlPokemon) {

        const response = await fetch(urlPokemon);
        const dataPokemon = await response.json();

        var id = dataPokemon.id;
        var name = dataPokemon.name;

        console.log(id, name);
    }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First thing’s first: "Why are they coming back in random order?" – Because you are not awaiting each response. Instead you are firing off all 20 async calls which can come back in any order, so that’s why they are logging in a random order.

In order to fix this, there are a few changes I’d recommend:

  1. Extract your apiPokemon function out of your loop so it doesn’t get recreated for each loop iteration
  2. Return the entire data object from your apiPokemon function
  3. Add all of the apiPokemon requests to an array and await them with Promise.all()
  4. Log the output of the Promise.all() and you’ll see that they will now always be in correct order
async function apiPokemon(urlPokemon) {
  const response = await fetch(urlPokemon);
  const dataPokemon = await response.json();

  return dataPokemon;
}

async function getPokemon(startIndex, stopIndex) {
  let requests = [];
  for (var i = startIndex; i <= stopIndex; i++) {
    requests.push(apiPokemon("https://pokeapi.co/api/v2/pokemon/"+i)); 
  }
  let pokemon = await Promise.all(requests);
  for (let data of pokemon) {
    console.log(data.id, data.name);
  }
}

getPokemon(1, 20)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading