javascript - Promise.all 在 fetch 解决之前返回

标签 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 来实现的,而不是口袋妖怪。为什么?

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 之前缺少 return:

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

关于javascript - Promise.all 在 fetch 解决之前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48885248/

相关文章:

javascript - ReactJS:未捕获( promise 中) this.setState 不是一个函数

javascript - 解决 promise 中的 promise 顺序

node.js - 如何使用 Amazon DynamoDB JavaScript SDK 与 Promise

javascript - jQuery 似乎无法识别 Ajax 调用状态代码 403 的不同字符串

javascript - 我的计算器没有输出任何内容并且在任何测试中都没有给出错误?

javascript - 如何在 iOS 9.3+ 上从网页打开 Safari 的设置

javascript - 在我的 React 应用程序中出现解析错误

javascript - 当用户滚动div顶部时如何获取事件?

javascript - 连接两个 promise

javascript - 如何访问使用 $.getScript 运行的脚本中的函数或变量