[英]Can't iterate over my API generated array using the forEach() method
在使用 console.log/debugger 進行故障排除后,我似乎無法在 function addListItem 中的 forEach 方法調用中迭代我的 API 生成的數組。
但是,我可以看到在 loadList function 的 forEach 迭代中填充了 pokemonNameList 數組。
我究竟做錯了什么?
const apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=15';
const pokemonNameList = [];
function getAll() {
return pokemonNameList;
}
function add(pokemon) {
if (typeof pokemon === 'object') {
pokemonNameList.push(pokemon);
}
}
function loadList() {
return fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
data.results.forEach((item) => {
fetch(item.url)
.then((response) => response.json())
.then((inneritem) => {
const pokemon = {
name: inneritem.name,
height: inneritem.height,
weight: inneritem.weight
};
add(pokemon);
console.log(pokemonNameList);// I can see the array here
});
});
})
.then(() => {
console.log(pokemonNameList);
})
.catch((e) => {
console.error(e);
});
}
function addListItem(pokemon) {
console.log('I cannot see this console log');//This does not show up
const card = document.createElement('li');
const cardbody = document.createElement('div');
const name = document.createElement('h1');
card.classList.add('card');
cardbody.classList.add('card-body');
name.classList.add('card-title');
name.innerText = pokemon.name;
cardbody.appendChild(name);
card.appendChild(cardbody);
pokemonList.appendChild(card);
}
loadList()
.then(() => {
getAll().forEach((item) => {
console.log('Hello from inside the forEach');//I cannot see this
addListItem(item);
});
})
.catch((e) => {
console.error(e);
});
問題是您沒有等待內部fetch(item.url)
,因此當您調用 getAll 時,還沒有推送任何項目。
您可以通過將 forEach 更改為 map、返回 promise 並添加 promise.all 來做到這一點......像這樣:
function loadList() {
return fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
return Promise.all(data.results.map((item) => {
return fetch(item.url)
...
我創建了所有功能,直到您提到錯誤的地方
const pokemonNameList = []; // Pokemon Array const apiUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=15'; // API URL // To prevent duplicates, in case of calling the loadList function multiple times, i'm passing the index from the response, to replace the element at the same index const add = (pokemon, index) => pokemonNameList[index] = (pokemon); const getAll = _ => pokemonNameList; // Short arrow function to return pokemonNameList async function loadList() { const response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=5'); const result_1 = await response.json(); Promise.all(result_1.results.map((item, index) => fetch(item.url).then(response_1 => response_1.json()).then(({ name, height, weight }) => add({ name, height, weight }, index)))).then(() => getAll().forEach(pokemon => console.log(pokemon))); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.