I'm having a problem I'm calling my function getPokemons
that brings information from an api, my problem is that I want to make an array that createPokemons
returns the generated array at the end of the second function. But it doesn't.
const getPokemons = async () => {
const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20');
const data = await res.json();
function createPokemon(results) {
const pkArray = []; // Retornar este arreglo.
results.forEach(async (pokemon) => {
const pokeRes = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemon.name}`);
const pokeData = await pokeRes.json();
pkArray.push(pokeData);
});
return pkArray;
}
const pkData = createPokemon(data.results);
console.log(pkData) // [];
};
change the
forEach
for afor
The reason:
forEach
it will execute an asynchronous function for each element of the array which makes it harder to wait withasync/await
. Instead,for
it will be executed sequentially, waiting for each request.It would look like this: