0

I am working on this Pokemon API app where I want to model object for each individual Pokemon. My function looks like this:

const createPokemonObject = () => {

    fetchPokemonData().then(data => {
    const { results } = data

    results.map(async (pokemon) => {
        
        const {  url } = pokemon
        const data = await fetch(url)
        const response = data.json()

        response.then(data => {
            const { name, id, sprites: {other: {dream_world: {front_default}}}, types, weight, stats } = data

                const pokemonObject = {
                    id: id,
                    name: name, 
                    image: front_default,
                    weight: weight,
                    types: types,
                    stats: stats
                }
                console.log(pokemonObject)
            })
        })
    })
}

fetchPokemonData() function is returning promise, which is asynchronous code, and then I am using async function again inside of array to get definite data and model the object for each Pokemon. Object looks like this:

Pokemon Object

My question is how can I rewrite this createPokemonObject() function so that is returns a promise on which I can later chain then() function with all pokemonObject objects inside, with whom I could make some UI elements later?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Marin
  • 53
  • 6
  • 1
    Return a `Promise.all` called on the array of promises resulting from mapping over the results – CertainPerformance Oct 08 '22 at 01:14
  • Thank you for the answer, but I still don`t understand what you mean. – Marin Oct 08 '22 at 15:31
  • You're not returning your promises. You need to `return fetchPokemonData().then(...` and also `return results.map(...` and also `return response.then(...`. It should return an array of promises. – slebetman Jul 26 '23 at 14:43

0 Answers0