I am currently facing an issue uploading a local .json file to my web application. I have managed to display the file in the dev tools, but I am unable to make it accessible for further use. It seems like the problem lies in how I handle (or fail to handle) the asynchronous behavior of the file reader.
Everything is set up in an Angularjs (1.7) environment, which explains the syntax used in the snippet. The goal is to showcase the retrieved data on an openlayers map.
this.jsonSelected = function(newFile) {
let reader = new FileReader();
let result = 'empty';
reader.readAsText(newFile);
reader.onload = function(e) {
result = e.target.result;
console.log('in onload', result);
this.result = e.target.result;
};
console.log(this.result);
};
this.test = function() {
console.log(this.file);
}
I anticipated the code to log the file content twice. Once at "console.log ('in onload', result);" and another time at "console.log (this. result);". The first one functions as expected, however, the second one does not. Additionally, the order of logs in the console appears to be inverted, with "console.log (this. result)" showing up before the inload log, as shown in this console screenshot.
I have attempted various modifications, such as switching the names around and adjusting the references to "this.", yet no success. This leads me to believe that I am mishandling the asynchronous data. The details in the screenshot, particularly the timing of the log lines, hint at a timing issue.