使用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
s而不是Pokemons。为什么呢?
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)
})

答案 0 :(得分:2)
你错过了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
})
)