I want to get a value from nested function (var hash) but the return is not working. I've read that my problem is that I can't use return inside an asynchronous function and that I should use promises instead, after some research I found that promises will generate some compatibility problem with browsers. So I'm looking for a simple way to get my result.
This function is used to get MD5 hash with SPARKMD5
function calcmd5(file) {
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = 2097152, // Read in chunks of 2MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
fileReader.onload = function (e) {
console.log('read chunk nr', currentChunk + 1, 'of', chunks);
spark.append(e.target.result); // Append array buffer
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
console.log('finished loading');
var hash = spark.end();
console.log( hash );
return hash; // I want this result
//console.info('computed hash', spark.end()); // Compute hash
}
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
function loadNext() {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
}
var result = calcmd5(file); // use to get the hash