我試圖擺弄從公共 API 獲取資料,然后在 React 組件中顯示該資料,但 React 部分并不重要,這主要是一個 js 問題。我將
事實上,如果我嘗試控制臺日志 pokemons.length 我得到 0
什么會導致這個?我在提取請求中做錯了什么嗎?
uj5u.com熱心網友回復:
因此,您創建了一個空陣列。
你回圈遍歷陣列,觸發一堆異步請求,作為副作用,當承諾完成時,這些請求將填充空陣列。
您立即回傳陣列,而無需等待承諾完成。
發生這種情況時,請求可能甚至還沒有離開您的機器。
此時陣列為空。
相反,如果您將您的函式宣告為async并且map您IDs使用一個新的 promise 陣列,然后使用 等待它們全部Promise.all,那么 promises 將能夠在函式回傳之前完成,并且決議后的值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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/534336.html
