Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value calculated from javascript FileReader onload event [duplicate]

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.

like image 737
domoarigato Avatar asked Apr 24 '15 10:04

domoarigato


People also ask

What does FileReader result return?

The FileReader result property returns the file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.

What is FileReader onload?

The FileReader. onload property contains an event handler executed when the load event is fired, when content read with readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText is available.

What is FileReader in Javascript?

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read.


1 Answers

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);
}
like image 109
Vigneswaran Marimuthu Avatar answered Sep 20 '22 23:09

Vigneswaran Marimuthu