0

Here's my file reader:

p.read = function(file) {
    var fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = function(e) {

        return e.target.result;
    }
}

But nothing is returned? Any ideas why?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • Have you tried `fileReader.result`? – Ian Mar 06 '14 at 16:09
  • 2
    You *cannot* `return` anything from an asynchronous callback function. See also [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi Mar 06 '14 at 16:09
  • @Bergi I don't know how I didn't see that `return`. For some reason I thought they were printing the value and was having trouble with that – Ian Mar 06 '14 at 16:12
  • `return` returns from the function it's in. That return is nested in *another* function which will be executed at some point in the future. It has no impact on the outer function. – user229044 Mar 06 '14 at 16:17

2 Answers2

0

I'm afraid that you cannot return it from a callback function

try to separate it in another function

I hope I helped

0

This is an async function. That mean that if you do this :

p.read = function(file) {
    var fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    console.log('a');
    fileReader.onload = function(e) {
        console.log('b');
        return e.target.result;
    }
}

and :

console.log('hello');
p.read('file');
console.log('c');

You will get

hello
c
a
b

Because javacript is asynchronous. Very nice b/c like so, your code is non-blocking: it is really easy to do something while reading a big file.

In your example, you have to do :

p.read = function(file, callback) {
    var fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    fileReader.onload = function(e) {
        callback(e.target.result);
    }
}

And to run:

p.read('file', function(content) {
   console.log(content);
});
Vinz243
  • 9,654
  • 10
  • 42
  • 86