8

I have this function:

function doStuff(range, file) {
    var fr = new FileReader();
    var hash = '';
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        return hash;
    };
    fr.readAsArrayBuffer(file);
    return hash;
}

Right now, the function completes before the onload event is finished, so doStuff always returns "". I think a callback is what I need, but I'm new to javascript, and I can't wrap my mind around how to implement it in this case.

0

1 Answer 1

17

File reading using File Reader is asynchronous operation. Place your logic inside the onload function of file reader.

function doStuff(range, file) {
    var fr = new FileReader();
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        /* Place your logic here */
    };
    fr.readAsArrayBuffer(file);
}

You can even pass a callback function that will be executed once the file is read.

function doStuff(range, file, callback) {
    var fr = new FileReader();
    fr.onload = function (e) {
        var out = "stuff happens here";
        hash = asmCrypto.SHA256.hex(out);
        /* Assuming callback is function */
        callback(hash);
    };
    fr.readAsArrayBuffer(file);
}
3
  • 1
    No idea. There seems to be nothing wrong with this answer. Apr 24, 2015 at 10:44
  • 1
    @Phylogenesis Even same here. I don't know why ppl do down voting simply :( Apr 24, 2015 at 10:44
  • 1
    It can also be noted that there is a synchronous FileReader API available in Firefox only (and even then only in a web worker context). Apr 24, 2015 at 10:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.