【问题标题】:Nested fetch is undefined is Svelte {#await} block [duplicate]嵌套提取未定义是 Svelte {#await} 块 [重复]
【发布时间】:2022-01-09 01:40:33
【问题描述】:

我正在使用 poke api https://pokeapi.co/ 来学习 Svelte - 我使用 fetch 来获取 pokemon 列表并使用嵌套 fetch 调用来获取获取的每个 pokemon 的图像 url。在 console.logging 结果时,口袋妖怪数组看起来很好,附加了 imgUrl。

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;
}

但是,该附加值似乎在 {#await} 块内未定义

{#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}

这里有什么问题?

【问题讨论】:

标签: javascript async-await fetch svelte


【解决方案1】:

就像 cmets 中提到的那样,您需要 awaitforEach 中所做的事情。为此,您需要将response.pokemon.forEach( 转换为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;
}

这是一个有效的REPL

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2021-11-26
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多