2 回答

TA貢獻1818條經驗 獲得超11個贊
您的問題是,雖然每個單獨的請求都是異步的,但您在所有 150 個請求完成之前都會返回。在下面的 for 循環中,不是鏈接到請求并立即推送,而是將 promise 推送到數組中。然后,在循環之后,返回一個 Promise,一旦請求了所有 150 個 Promise 并將其推送到數組中,該 Promise 就會解析。fetchrequestspokemons
const fetchPokemon = function() {
const pokemons = [];
const requests = [];
for (let i = 1; i <= 150; i++) {
const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
const prom = fetch(url).then((r) => r.json());
requests.push(prom);
}
return new Promise((resolve) => {
Promise.all(requests)
.then((proms) =>
proms.forEach((p) => pokemons.push({
name: p.name,
id: p.id
}))
)
.then(() => resolve(pokemons));
});
};
fetchPokemon().then(console.log);

TA貢獻1809條經驗 獲得超8個贊
在這里發布這個,作為一個更簡單,更簡潔和最好的例子使用異步/等待。
并行 fetch,具有迭代第一個順序就緒 fetch 響應的功能。即:如果前 25 個 fetch 完成,它將按順序迭代前 25 個,而無需等待后一個 125。
const fetchPokemon = async function() {
const pokemons = [];
for (let i = 1; i <= 150; i++) {
const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
const data = fetch(url).then(res => res.json())
.then( ({name, id}) => ({name, id}) );
pokemons.push(data);
}
for await (const pokemon of pokemons) {
console.log(pokemon);
}
// or if you need to use the index:
for (let i = 0; i < pokemons.length; i++) {
console.log(await pokemon[i]);
}
};
fetchPokemon();
添加回答
舉報