I created an array of objects (topAnimes) inside the request.onload() function, but I can't access a specific index of that array outside the scope of onload(), even if I declare the array as a global variable (at the beginning of the script). Inside the scope of onload() function, i can access to the Array correctly. I need to be able to use the Array "topAnimes" everywhere, i mean, like every global variable.
What could be the problem? The only solution would be to call the rest of the code from the "onload()" handler function, passing the Array as an argument?
I think maybe the controller function (onload) is executed after each external code, so at the time of reading console.log(topAnimes[0]), the array is empty.
Thanks for reading!
const topAnimes = [];
class Anime{
constructor(title, synopsis, status, episodes, genres, image){
this.title = title;
this.synopsis = synopsis;
this.status = status;
this.episodes = episodes;
this.genres = genres;
this.image = image;
}
}
class AnimeNode{
constructor(anime){
this.anime = anime;
this.node = document.createElement('div');
this.titleNode = document.createElement('h1');
this.synopsisNode = document.createElement('p');
this.episodesNode = document.createElement('p');
this.statusNode = document.createElement('p');
this.imageNode = document.createElement('img');
this.genreNode = document.createElement('ul');
}
static init(){
// to do
}
}
// HTTP request
const request = new XMLHttpRequest();
request.responseType = 'json';
request.onload = (e) => createList(e);
request.open('GET', "https://api.jikan.moe/v4/top/anime");
request.send(null);
function createList(e){
const animeList = e.target.response.data;
animeList.forEach(element => {
topAnimes.push(new Anime(
element.title,
element.synopsis,
element.status,
element.episodes,
element.genres,
element.images.jpg.image_url
));
});
console.log(topAnimes[0]); // no problem to see the object
}
console.log(topAnimes[0]); // undefined
console.log(topAnimes); // i can see the Array in the browser console and expand it