Finally, my first question here on stackoverflow. I can guarantee you that I have searched for related answers, but no one fits my problem. I am learning JavaScript now, having a background in .NET and C++, but I can't get this piece of code to do what I expect. I am copying here one of the many versions, with possible a questionable placement of the return statement, but maybe you can help me out with this.

function readFile(file) {                                                       
    var reader = new FileReader();
    reader.onload = readSuccess;                                            
    function readSuccess(evt) {                        
        var text = evt.target.result; 
        return text;                                      
    };
    reader.readAsText(file);                                  
} 

What I try here, is reading a file that is accesed in HTML via a tag input with type="file". Everything goes just well inside the code up to that part. I used Chrome Console and Firebug, to capture the return of the function into a variable in the Console, like:

var x = readFile(aFile);

And what I get is an 'undefined' message. Using breakpoints, I can see the text content in the return statement and it is correctly filled! But the text isn't returned! I've seen questions related, but they get around the problem using innerHTML and other kind of tricks that I do not want to do here, because the result of this function is supposed to be consumed by another JS function, and not to update any part of the DOM.

Thank you very much in advance for your time.

有帮助吗?

解决方案

You are getting undefined because that's what readFile(aFile) returns (i.e. nothing). Just like with event listeners, there are various ways to get event data, one of them would be callbacks. Here's your code modified to use one:

function readFile(file, cb) {
    var reader = new FileReader();
    reader.onload = readSuccess;
    function readSuccess(evt) {
        cb(evt.target.result)
    };
    reader.readAsText(file);
}

var x;

readFile(aFile, function (data) {
    x = data;
});

I've added function as readFile's second argument, which will be called when the file is read with data passed into it. All variable assigning are to be done inside callback.

As for other ways to achieve similar result, there are also promises and generators, but you probably should understand JS async basics first.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top