Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange
, causing the getData
method to be called before the constructor finishes executing. This leads to an undefined data result. How can I ensure that the methods in this class wait for the file to finish loading before proceeding? Since I'm relatively new to async code and promises, please explain it to me like I'm 5 years old.
The current workaround in my code involves wrapping the method in a timeout, which somewhat addresses the issue. However, utilizing the synchronous version of request.open
is not recommended due to performance concerns. So, that option is off the table as well.
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
}
}