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);
}
}
>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:
- Extract your apiPokemon function out of your loop so it doesn’t get recreated for each loop iteration
- Return the entire data object from your apiPokemon function
- Add all of the apiPokemon requests to an array and await them with
Promise.all() - 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)