I am trying to make a class where a filename is passed to the constructor, the file is loaded using an XmlHttpRequest, and the result is stored in a class variable. The issue is that request.onreadystatechange
is an asynchronous function and therefore the method getData
ends up being called before the constructor completes. The result of the data is therefore undefined. How can I make sure the methods of this class wait for the file to be loaded before running. I'm rather new to async code and promises so please explain like I'm 5.
Wrapping the method in a timeout as shown in my code fixes the issue somewhat but that is an awful solution and the synchronous version of request.open
is depreciated because of obvious performance issues so that is not a solution either unfortunately.
test.html
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="test.js"></script>
<script>
let test = new testClass('test.json')
console.log(test.getData)
</script>
</body>
</html>
test.js
class testClass {
constructor(filename) {
this.loaded_data = undefined
let request = new XMLHttpRequest()
request.overrideMimeType('application/json')
request.open('GET', filename)
request.onreadystatechange = () => {
if (request.status == '200' && request.readyState == 4) {
/* Load and parse JSON here */
this.loaded_data = 'foo'
}
}
request.send()
}
get getData() {
setTimeout(() => {
console.log(this.loaded_data)
}, 500);
return this.loaded_data
}
}