I'm having an issue accessing a variable that is written in a JavaScript promise in the constructor of a class file. I have only used promises once, and despite doing some additional reading on them, it's still a little confusing to me, so I assume this is where I'm going wrong.
Below is the code in question:
Guild.js
- This is the class with a variable set through a promise
class Guild extends MapObject {
constructor(x, y, floor, type, name) {
super(x, y, floor);
this.levels = [];
this.type = type;
this.name = name;
this.id = this.type + this.position.x + this.position.y;
this.guildSelector().then((gData) => {
this.guildData = gData;
this.addLevels(this.name);
this.setTip();
});
}
setTip() {
this.tip = this.name;
}
guildSelector() {
return new Promise((resolve, reject) => {
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);
resolve(this.guildData);
}
})
}
}
map-maker.js
- Main class utilising instances of Guild.js
function createGuildObject(x, y, floor, type, name) {
return new Promise((resolve, reject) => {
console.log("createGuildObj");
currentMap.objects.push(new Guild(x, y, floor, type, name));
var currentGuild = currentMap.objects[currentMap.objects.length - 1];
console.log(currentGuild.guildData);
resolve(currentGuild);
});
}
So the problem I have is when I push a new instance of guild.js to my map class (essentially a container of objects) I can access every variable of the guild except the one set during the promise (this.guildData
).
Where I'm really confused is if I type:
console.log(currentGuild.guildData);
directly after initialising the guild instance I see null
.
But if I type:
console.log(currentGuild);
I see the guildData variable with all of its content:
Any suggestions?