const fetchPokemon = async (id) => {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const data = await response.json();
return data;
};
const getStarterPokemon = () => {
const ids = [1, 2, 3]
const pokemon = [];
ids.forEach(async (id) => {
const result = await fetchPokemon(id);
pokemon.push(result);
});
return pokemon
}
getStarterPokemon()
await-ing inside of a forEach will only end in pain. There are a few different ways to fix this, but here’s one using a for of loop.
const fetchPokemon = async (id) => {
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
if (!response.ok) {
throw new Error(`Network response was not ok: ${response.statusText}`);
}
const data = await response.json();
return data;
};
const getStarterPokemon = async () => {
const ids = [1, 2, 3]
const pokemon = [];
for (const id of ids) {
const result = await fetchPokemon(id);
pokemon.push(result);
};
return pokemon
}
await getStarterPokemon()