I'm still quite a noob at Javascript and one thing that I'm struggling to wrap my head round is forcing synchronicity into a primarily asynchronous programming language.
I have a function that loads a decent size JSON file and another function that utilises the return of this function.
I have read a lot of other threads about similar issues and keep seeing very different solutions, I was just curious what the best way to handle this would be.
Constructor calling the two functions -
class Guild extends MapObject {
constructor(x,y,floor,type,name) {
super(x,y,floor);
this.levels = [];
this.type = type;
this.name = name;
this.guildSelector();
this.addLevels(this.name);
this.setTip();
}
guildSelector function that loads the JSON and returns it as this.guildData
guildSelector(){
var oReq = new XMLHttpRequest();
this.guildData = null;
oReq.onload = reqListener;
oReq.open("get", "/json/guilds.json", true);
oReq.send();
function reqListener() {
this.guildData = JSON.parse(this.responseText);
console.log(this.guildData);
return this.guildData;
}
}
addLevels function that currently runs before this.guildData
is populated with the JSON causing it to crash as it can't find .guilds of null.
addLevels(name) {
if(name == "default"){
this.name = "lowerSchoolOfEndurance";
}
console.log(this.guildData);
this.guildData.guilds.forEach(function(guild) {
console.log(guild.name);
if(guild.name == name){
for(var i = 1; i <= guild.levels.length; i++){
var guildStats = guild.levels[i-1];
for (var k in guildStats) {
console.log("Level "+i+" of the guild "+name+" increases "+k+" stat by "+guildStats[k]);
this.levels.push(guild.levels[i-1]);
}
}
}
});
return this.levels;
}
So the TL:DR would essentially be, what is the best way to not trigger my class that requires the JSON to be loaded until the JSON is loaded.
Kind Regards, Earl Lemongrab