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.