I'm trying to make a pokedex for a school project, and am using JS for doing so. I found this api called pokeapi, and since it uses JSON, I thought of just getting the data in the page and returning a json of it, however when I try to use the method I created to do a request in a for loop, it doesn't seem to work, only working on the last element of the for loop:
let request = new XMLHttpRequest();
const getJSON = (link, action) => {
request.open("GET", link);
request.send();
request.onload = () => {
if (request.status === 200) {
let json = JSON.parse(request.response);
action(json);
} else {
console.log(`e:${request.status} ${request.statusText}`);
}
}
}
let counter = 1;
getJSON("https://pokeapi.co/api/v2/pokedex/1/", (json) => {
json.pokemon_entries.forEach((poke_entry) => {
getJSON(poke_entry.pokemon_species.url, (poke_sp) => {
console.log(poke_sp);
//console loggin poke_sp only shows one console log, the last member of `json.pokemon_entries`
})
});
});
This is because you have created a single XHR object.
Every time you make a request with it, you cancel the previous request.
Create a new XHR object (inside the getJSON function) for each request.
i.e. swap the order of
let request = new XMLHttpRequest();
and
const getJSON = (link, action) => {