0

Please check the following code:

function loadCSV(fileInput) {
    var reader = new FileReader();
    reader.readAsText(fileInput);
    var result = {};
    var file = {};
    var error = {};
    reader.onload = function(evt) {
        var csv = evt.target.result;
        var data = $.csv.toArrays(csv);
        file[fileInput.name] = data;
        result['file'] = file;
        console.log(result);
    }
    reader.onerror = function() {
        error = {
            'message': 'Unable to read ' + fileInput.name
        }
        result['error'] = error;
    }
    console.log(result);
    return result;
}

The result within the reader.onload section is correct, but the result returned is empty. I know this is because I am updating the result in a sub-function reader.onload and I also know using callback for loadCSV is a solution to solve the problem. But I want to know whether there is any way that I can make loadCSV returning the updated result.

Thanks.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Benson
  • 275
  • 2
  • 6
  • 12
  • 2
    Look for the promise pattern, e.g., [jQuery Deferred](http://api.jquery.com/category/deferred-object/). – Sirko Mar 06 '14 at 18:03
  • 2
    The filereader API is asynchronous, your outer function returns before the callback is executed. You can't return from an asynchronous function. See also http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Felix Kling Mar 06 '14 at 18:04
  • @FelixKling - That's a good thread. – Dissident Rage Mar 06 '14 at 18:10

1 Answers1

1

Any event handler attached to FileReader.onload is going to be an asynchronous function, which means it's done when it says it's done. If you want to do something with the result, you're going to have to do it inside your handler function.

Dissident Rage
  • 2,610
  • 1
  • 27
  • 33