0

I'm trying to wrap my head around the reader object.

I have this function, currently I console.log(this.result), but I would like to return it instead after the event is triggered.

readFile = function(fs, filename){
    fs.root.getFile(filename, {}, function(fileEntry){
        //this object reads files.
        var reader = new FileReader();
        //register callback for read files
        reader.onloadend=function(e){
            //this is what i want to return
            console.log(JSON.parse(this.result));
        };

        //read file-function
        fileEntry.file(function(file){
            reader.readAsText(file);
        },errorHandler);

    },errorHandler);
};

Simply retrurning it like this won't work

readFile = function(fs, filename){
    fs.root.getFile(filename, {}, function(fileEntry){
        //this object reads files.
        var reader = new FileReader();
        //register callback for read files
        reader.onloadend=function(e){
            //this is what i want to return
            return JSON.parse(this.result);
        };

        //read file-function
        fileEntry.file(function(file){
            reader.readAsText(file);
        },errorHandler);

    },errorHandler);
};

console.log(readFile(foo, bar)) will output undeifined, it seems as though the returns get triggered before reader.onloadend is run.

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • 1
    [How to return the response from an asynchronous call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – adeneo Mar 20 '15 at 15:14
  • adeneo, that doesn't apply, it's an event, not a callback, updated question. – Himmators Mar 20 '15 at 15:16
  • In what way is it *not* a callback? The duplicate's solution applies here completely. – JJJ Mar 20 '15 at 15:17
  • My bad, I thought the question was about using callbacks. Yes, it's a duplicate. – Himmators Mar 20 '15 at 15:21
  • I didn't close it, but I was going to, as it's actually a perfect duplicate. The `FileReader` is async, and you can't return from an asynchronous call, the duplicate tells you why, and how to solve it. – adeneo Mar 20 '15 at 15:21

1 Answers1

0

I return the value by passing a callback:

readFile = function(fs, filename, callback){
    if(!fs){
        console.log('no filesystem registered')
        return;
    }
    fs.root.getFile(filename, {}, function(fileEntry){
        //this object reads files.
        var reader = new FileReader();
        //register callback for read files
        reader.onloadend =  function(e){
            callback(JSON.parse(this.result))
        };

        //read file-function
        fileEntry.file(function(file){
            reader.readAsText(file);
        },errorHandler);

    },errorHandler);
};

errorHandler = function(e) {
  console.log('Error: ', e);
};
Himmators
  • 14,278
  • 36
  • 132
  • 223