Promise.all在fetch解决之前返回

时间:2018-02-20 12:24:14

标签: javascript promise

使用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)
})




1 个答案:

答案 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
    })
)