【发布时间】: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}
这里有什么问题?
【问题讨论】:
-
forEach不处理异步。见:Using async/await with a forEach loop
标签: javascript async-await fetch svelte