[英]Javascript JSON Fetch with await returns data but its function return an empty array
我试图摆弄从公共 API 获取数据,然后在 React 组件中显示该数据,但 React 部分并不重要,这主要是一个 js 问题。 我正在使用PokeApi进行学习,我使用请求中需要的数据创建一个新的 object,然后将该 object 推送到 function 在调用时返回的数组:
// fetchPoke() function
let pokemons = []
// IDs is just an array with 20 random numbers between a range
IDs.forEach(async (id) => {
let url = `https://pokeapi.co/api/v2/pokemon/${id}`
await fetch(url)
.then((res) => {
if (!res.ok) {
console.log(`${id} not found`)
} else {
return res.json()
}
})
.then((data) => {
let pokemon = {}
pokemon.id = data.id
pokemon.name = data.name
pokemon.image = data.sprites.other.dream_world.front_default
pokemons.push(pokemon)
})
})
// function returns the array of object
return pokemons
但每当我称这个为 function
let pokemons = fetchPoke()
然后记录它
console.log(pokemons)
虽然我可以看到内容,但它说它是一个 0 的数组:
事实上,如果我尝试控制台日志 pokemons.length 我得到 0
什么会导致这个? 我在提取请求中做错了什么吗?
因此,您创建了一个空数组。
你循环遍历数组,触发一堆异步请求,作为副作用,当承诺完成时,这些请求将填充空数组。
您立即返回数组,而无需等待承诺完成。
发生这种情况时,请求可能甚至还没有离开您的机器。
此时数组为空。
相反,如果您将 function 声明为async
,并将您的IDs
map
声明为一个新的承诺数组,然后使用Promise.all
等待它们,那么承诺将能够在 function 返回之前完成,并且解析值为Promise.all
将是一个包含你的口袋妖怪的数组。
async function getSomePokemons(IDs) { // note, this is an async function
const promises = IDs.map((id) =>
fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
.then((res) => {
if (!res.ok) {
console.log(`${id} not found`)
// implicitly resolves as undefined
} else {
return res.json()
}
})
.then((data) => (data ? { // data might be undefined
id: data.id,
name: data.name,
image: data.sprites.other.dream_world.front_default
} : undefined))
)
const pokemons = await Promise.all(promises);
return pokemons;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.