Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!