0

Whenever I log the result of the function, it shows the expected data (an array of objects) but I want to further manipulate the values but whenever I try to access it, results in an undefined value. The result of console.log(fetchTypeData().length) is always 0.

const fetchTypeData = () => {
      let data = [];
      const typeDataUrl = ['https://pokeapi.co/api/v2/type/10', 'https://pokeapi.co/api/v2/type/3'];
      typeDataUrl.forEach(async (dataUrl) => {

        const typeData = await fetch(dataUrl).then((res) => res.json());
        const damageRelations = await typeData.damage_relations; // Return an Object
        const damageMultiplier = Object.keys(damageRelations); // Returns an array
        damageMultiplier.forEach((multiplier) => {
          let position;
          let damage;
          switch (multiplier) {
            case "double_damage_from":
              position = "defence";
              damage = 2;
              break;

            case "double_damage_to":
              position = "attack";
              damage = 2;
              break;

            case "half_damage_from":
              position = "defence";
              damage = 0.5;
              break;

            case "half_damage_to":
              position = "attack";
              damage = 0.5;
              break;

            case "no_damage_from":
              position = "defence";
              damage = 0;
              break;

            case "no_damage_to":
              position = "attack";
              damage = 0;
              break;

            default:
              break;
          }
          damageRelations[multiplier].forEach((type) => {
            const newItem = {
              position: position,
              damage: damage,
              type: type.name,
            }
            data.push(newItem);
          });
        })
      })
      return data;
    }
console.log(fetchTypeData())          // Logs expected array [{..},{..},{..}...]
console.log(fetchTypeData().length)   // Logs 0

I tried calling the function inside another async function so I can assign it to another variable but it's still the same result.

const getData = async () => {
   const data = await fetchTypeData();
   console.log(data);    // Logs an array of objects as expected [{..},{..},{..}..]
   console.log(data.length) // Logs 0
}
getData()

EDIT: While I do now understand why I am able to log the return value of fetchDataType() it still doesn't solve my issue where I can't access it for further manipulation.

EDIT 2: I manage to make a work around for the issue by limiting the fetch calls in fetchTypeData() and calling it within an async function where it iterates an array of URLs and use it as an argument for fetchTypeData().

const genTypeData = async () => {

      const typeDataUrl = pokemonData.types.map((obj) => obj.type.url);
      const typeDamage = await Promise.all(typeDataUrl.map(dataUrl => fetchTypeData(dataUrl)))
// Logs as an array of 2 arrays [[{...}...],[{...}...]]
      const typeDamageData = typeDamage.flat() // Calls the array.flat() method to create a single layer array
      const filteredData = filterTypeData(typeDamageData)  // Can now be manipulated
 }
  • @CertainPerformance That's just an explanation for the symptom but not for the actual problem -> [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Andreas Oct 27 '22 at 07:32

0 Answers0