0
document.addEventListener('DOMContentLoaded', function() {
    let fileInput = document.getElementById("fileInput")
    let displayArea = document.getElementById("displayArea")

    fileInput.addEventListener("change", (e) => {
        let file = fileInput.files[0];

        let reader = new FileReader();

        reader.onload = (e) => {
            displayArea.innerText = e.target.result;
        };

        reader.onerror = (e) => {
            console.error("File could not be read! Code " + e.target.error.code);
        };

        reader.readAsText(file);

        console.log(displayArea.innerText);
    });
}, false);

<input type="file" id="fileInput">
<div id="displayArea"></div>

div contains the text, but console.log gets <empty string>.

I think it logs before reader.onload.

I tried to do something with async and await, but without any success.

Thanks a lot!

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48
  • Move console.log into reader.onload after div innerText set – Nilanka Manoj Mar 14 '20 at 14:38
  • `onload` is a callback function. Is executed when the reader loads (hence the onload name). That means that the `console.log` is executed before the onload callback is executed. Being the code before don't means that runs before. It runs when it has to run. That's keyword here to look up in Google is `asyncrhonous`. – Jorge Fuentes González Mar 14 '20 at 14:51
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Terry Mar 14 '20 at 14:54
  • Move `console.log(displayArea.innerText);` into the `onload` callback. – Terry Mar 14 '20 at 14:55

0 Answers0