0

I am using poke api https://pokeapi.co/ to learn Svelte - I use fetch to get the list of pokemons and nested fetch call to get the image url of every pokemon fetched. While console.logging the result, the array of pokemons is looking fine, with imgUrl appended.

JavaScript (Svelte):

async function fetchGroup() {
    const response = await fetch('https://pokeapi.co/api/v2/type/11').then(result => result.json());
    response.pokemon.forEach(async (elem, index) => {
        const imgUrl = await fetch(elem.pokemon.url).then(result => result.json().then(result => result.sprites.front_default))
        elem.pokemon = { ... response.pokemon[index].pokemon, ... { imgUrl : imgUrl }}
    })
    console.log(response.pokemon); // this log returns the correct obejct with imgUrl appended
    return response.pokemon;
}

However, that appended value seems to be undefined inside {#await} block

{#await pokemonsList}
    waiting...
    {:then response}
        {#each response as responseItem}
            {responseItem.pokemon.name} this is alright!
            {responseItem.pokemon.imgUrl} this is undefined 
        {/each}
    {:catch error}
        {error.message}
{/await}

What's wrong here?

xDrd
  • 3
  • 1
  • 2
    `forEach` doesn't handle async. see: [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – pilchard Jan 08 '22 at 12:06

1 Answers1

0

Like mentionned in the comments you need to await what you are doing in the forEach. To do so you will need to transform the response.pokemon.forEach( to await Promise.all(response.pokemon.map(:

async function fetchGroup() {
    const response = await fetch('https://pokeapi.co/api/v2/type/11').then(result => result.json());
    await Promise.all(response.pokemon.map(async (elem, index) => {
        const imgUrl = await fetch(elem.pokemon.url)
                    .then(result => result.json()
                    .then(result => result.sprites.front_default))
        elem.pokemon = { ... response.pokemon[index].pokemon, ... { imgUrl : imgUrl }}
    }))
    return response.pokemon;
}

Here is a working REPL.

johannchopin
  • 13,720
  • 10
  • 55
  • 101