0

I'm attempting to open and read a text file in JavaScript without using any direct HTML, just JavaSCript. However, because JavaScript is asynchronous the function is finished executing before i can select the file to read. Is there a callback function i can use to read the file only after i've selected it? I don't know why the code continues to execute before i've finished selecting my file. I can now get my file opened and read but i still cannot return the built text object. Here's the code i currently have:

        loadFileFromDisk: function (leaveHere) {
        var openFile = this.createElement("INPUT");
        openFile.setAttribute("type", "file");
        openFile.setAttribute("id", "openFile");
        var openElement = document.getElementById("openFile");

        openElement.addEventListener("change",
            function(changeEvent) {
                var selectedFile = changeEvent.target.files[0];
                var reader = new FileReader();

                reader.onload = function(e) {
                    var text = reader.result;
                    leaveHere(text);
                };
                reader.readAsText(selectedFile);
            }
        );

        openFile.click();

    };
user1789573
  • 515
  • 2
  • 8
  • 23
  • 2
    Well, you need to wait for the `change` event on the input… you cannot directly `return` the result. – Bergi Dec 07 '16 at 16:32
  • No. `click` does not take a callback. Use `openFile.addEventListener('change', …)` – Bergi Dec 07 '16 at 16:54
  • You [cannot `return` from an asynchronous function](http://stackoverflow.com/q/14220321/1048572) at all. Use a callback or promises. – Bergi Dec 07 '16 at 17:55
  • As a parameter to `loadFileFromDisk`. Then, instead of trying to `return text;`, call `callback(text);`. And of course you'll have to change how you are invoking the method everywhere. – Bergi Dec 07 '16 at 18:43

0 Answers0