0

I just noticed that the FileReader API skips the handleFiles(appCSV) and returns undefined instead.

appDictionary = handleFiles(appCSV);
dbDictionary = handleFiles(dbCSV);

My appCSV file size is just 2584729 bytes or only about 2.5 MB. Is the issue due to that?

This is strange since I am already using Chrome 57.

Kindly help me investigate and provide solutions or workarounds. Thanks!

Body of the handleFiles function:

function handleFiles(files) {
    // Check for the various File API support.
    if (window.FileReader) {
        // FileReader are supported.
        getAsText(files[0]);
    } else {
        alert('FileReader are not supported in this browser.');
    }
}

function getAsText(fileToRead) {

    let reader = new FileReader();
    // Handle errors load
    reader.onload = loadHandler;
    reader.onerror = errorHandler;
    // Read file into memory as UTF-8      
    reader.readAsText(fileToRead);

}

function loadHandler(event) {
    let csv = event.target.result;
    processDataToDictionary(csv);
}

function errorHandler(evt) {
    if (evt.target.error.name == "NotReadableError") {

        alert("Cannot read file!");

    }
}
JPaulPunzalan
  • 417
  • 1
  • 6
  • 20
  • 1
    Could you show the body of this `handleFiles` function ? But as it is written, I can already make an educated guess that you are not waiting for the onload event of the FileReader, all its `readAs...` methods are asynchronous. – Kaiido Apr 17 '17 at 05:23
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kaiido Apr 17 '17 at 05:24
  • @Kaiido Hi, I've posted the body of the `handleFiles` function. IT does not skip `dbDictionary = handleFiles(dbCSV);` though, only `appDictionary`. Kindly help me investigate. – JPaulPunzalan Apr 17 '17 at 06:17
  • 1
    So, `appDictionary` and `dbDictionary` are set to `undefined` when you do `= handleFiles(foo)` because `handleFiles` doesn't return anything. Now I'll guess that in `processDataToDictionary` you are setting `dbDictionary` to something. Anyway, don't use these `appDictionary` and `dbDictionary` variables after having called `handleFiles`, instead, wrap the following of the actions in a callback function, that will get executed e.g after `processDataToDictionary`. – Kaiido Apr 17 '17 at 06:24

1 Answers1

0

I have resolved my own issue. It was due to that the onLoad event of FileReader API is asynchronous.

So I've decided to put the handleFiles() function in the onchange() property the input type = 'file'.

JPaulPunzalan
  • 417
  • 1
  • 6
  • 20