Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda