0

I am fetching pokemon's name and image using a nested fetch method. I have successfully created pokemon objects. but I am unable to store them inside pokemonsArray. what I am doing wrong here? how can I store them inside an array what should be a good approach to do it please guide me?

const cards = document.querySelector(".cards");
const error = document.querySelector(".err");
const search = document.querySelector("#search");
let url = "https://pokeapi.co/api/v2/pokemon?limit=100&offset=0";

let pokemonsArray = [];

const createPokemons = (pokemon) => {
  pokemonsArray.push(pokemon);
};

const getPokemon = () => {
  fetch(url)
    .then((res) => {
      if (!res.ok) {
        throw new Error("data could not be fetched");
      } else {
        return res.json();
      }
    })
    .then((data) => {
      const pokemonArray = data.results;

      pokemonArray.map((pokemon) => {
        fetch(pokemon.url)
          .then((result) => {
            if (!result.ok) {
              throw new Error("could not fetch new url");
            } else {
              return result.json();
            }
          })
          .then((data) => {
            let pokemon = {
              name: data.species.name,
              image: data.sprites.other.home.front_default,
            };

            createPokemons(pokemon);
          });
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

console.log(pokemonsArray.length); // 0 !!! why result is 0;

getPokemon();
Hasan
  • 15
  • 4
  • 1
    You're storing them in the array just fine. But you're logging the array length **before** adding the objects! – Bergi Oct 01 '22 at 20:18
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Robin Zigmond Oct 01 '22 at 20:18

0 Answers0