Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  121] [ 2]  / answers: 1 / hits: 19436  / 9 Years ago, fri, april 24, 2015, 12:00:00

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.


More From » callback

 Answers
3

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

[#66916] Thursday, April 23, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
claudiofredye

Total Points: 583
Total Questions: 101
Total Answers: 115

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;