JS Variable not available outside function

E Lon Mask :

I have a little problem with a variable in my code.

I'm having a variable which gets declaired outside the function but then can not be accessed after it.

So first you input a file which is combined with this code:

input.addEventListener("change", sefunction);

Now this file (which is a HTML-file) should get parsed into a string:

var htmlInput;
var inputFile = "";
function sefunction() {
if (this.files && this.files[0]) {
    var myFile = this.files[0];
    var reader = new FileReader();
    reader.addEventListener('load', function (e) {
        inputFile = e.target.result;
        htmlInput = new DOMParser().parseFromString(inputFile, "text/html").documentElement;
        console.log(htmlInput);            //WORKING FINE
        });
    reader.readAsBinaryString(myFile);
    document.getElementById("starten").disabled = false;
    document.getElementById("myFile").disabled = true;
    console.log(htmlInput);                //NOT WORKING
    initialisation2();
  };   
};

Then, to test it, I want to console.log the htmlInput:

function initialisation2() {
    console.log(htmlInput);                //NOT WORKING
}

Now what happens: The first console.log gives me the content of htmlInput. The second and the third (in initialisation2()) don't.

Can someone tell me why? The variable is declared outside the very first function so it sould be available in the rest of the code. I need to parse the HTML-input-file like this because I want to be able to access things like htmlInput.getElementsByTagName('table').

Callum Hart :

The htmlInput variable is being assigned a value after the second console.log and initialisation2 are called. This is because FileReader is asynchronous, so htmlInput will be undefined until the file has been read.

Moving the initialisation2 call into the load callback will resolve this:

reader.addEventListener("load", function(e) {
  inputFile = e.target.result;
  htmlInput = new DOMParser().parseFromString(inputFile, "text/html").documentElement;
  initialisation2();
});

We can replicate what is happening using a timeout that mimics the asynchronousity of the file reader:

var htmlInput;

function sefunction() {
  setTimeout(() => {
    htmlInput = "Given htmlInput";
    initialisation2(); // logs "Given htmlInput"
  }, 1000);

  initialisation2(); // logs "undefined"
}

function initialisation2() {
  console.log(htmlInput);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=383435&siteId=1