Return value computed from onload javascript FileReader event

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; } 

At the moment, the function ends before the onload event completes, so doStuff always returns "". I think the callback is what I need, but I'm new to javascript, and I can't think about how to implement it in this case.

+5
source share
1 answer

Reading files using File Reader is asynchronous. Put your logic in the onload function to read files.

 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 after reading the file.

 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); } 
+8
source

All Articles