0

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
Eagle
  • 81
  • 1
  • 2
  • 11
  • 2
    http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Jonah Williams Oct 18 '15 at 22:15
  • Asynchronous functions/methods are supossed to do that. They don't "lock" your processes, so they don't expect to get a result. What you could do is to call an update method on another object you're expecting to update. `return` will simply quit of the handler function. – Alejandro Iván Oct 18 '15 at 22:15
  • What you've found out is that promises are not *natively* supported in older browsers. However, there are loads and loads of [implementations](https://promisesaplus.com/implementations) that you can use as a drop-in replacement or shim. – Bergi Oct 18 '15 at 22:17
  • Oh, and btw, you cannot defeat asynchrony. Even if you're using promises, `result` won't be the result but just a promise for it. You always will need callbacks somewhere. – Bergi Oct 18 '15 at 22:19
  • you can use a plain old callback if you don't like promises. – dandavis Oct 18 '15 at 23:39

0 Answers0