我希望通过一个Pokemon ID数组,通过从Pokemon API中获取来获取一个Pokemon对象数组。目标是从中获得
[1,2,3]
对此:
[
{name: "ivysaur", weight: 130, …},
{name: "venusaur", weight: 1000, …},
{name: "bulbasaur", weight: 69, …}
]
我已经仔细研究了这个线程“ How can I fetch an array of urls with Promise.all”,但是没有一个解决方案对我有用。我有相同的问题outlined in this answer,但是提出的解决方案仍然无法产生结果。
我的
Promise.all
满足于一个undefined
数组,而不是口袋妖怪。为什么?const pokemonIds = [1,2,3]
const pokemons = pokemonIds.map(id => {
fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
.then(res => res.json())
.then(json => {
console.log(json)
return json
})
})
Promise.all(pokemons).then(res => {
console.log('pokemon arr: ', res)
})
最佳答案
您在fetch
之前错过了回报:
const pokemons = pokemonIds.map(id => {
return fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
.then(res => res.json())
.then(json => {
console.log(json)
return json
})
});
要么:
const pokemons = pokemonIds.map(id =>
fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
.then(res => res.json())
.then(json => {
console.log(json)
return json
})
)