Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
Nested fetch is undefined is Svelte {#await} block

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda