0

I have this javascript code. I am converting blob to base64 here. The reader.onloadend function when called starts processing asynchronously. So console(reader.result) which should print after the function, prints before the function completion and gives wrong value(value before the change in function). I want to use the changed value of reader.result after completion of async onload function.

        var reader = new window.FileReader();
        reader.readAsDataURL(array); 
        reader.onloadend = kk=function() {
            base64data = reader.result;                
            //console.log(base64data );
            //document.write(base64data);
            //document.getElementById('display1').setAttribute('src',base64data);
            return base64data
            }
            console(reader.result)
  • Just move the log inside the onloadend handler. – Bergi Oct 11 '16 at 18:39
  • The commented statements were examples of getting to the data effectively.... why did you put them in comments? – trincot Oct 11 '16 at 18:42
  • I am using polymer for web application. This is just an example of usage in console. In actual I want to assign that base64 value to the element in polymer and I cannot assign that while in the function as it gives not defined error due to binding. I need the result out of that function. – Saransh Miglani Oct 12 '16 at 04:52

2 Answers2

0

Why not to call another method from the onloadend handler:

var reader = new window.FileReader();
        reader.readAsDataURL(array); 
        reader.onloadend = kk=function() {
            base64data = reader.result;
            // sync way - execution will start before the rest of the handler
            loadEndCtd(base64data);
            // or async way - execution will start after handler is done
            // setTimeout(function(){ loadEndCtd(base64data); },0);

            return base64data
            }

var loadEndCtd = function( data ){
    console.log(data);
}
Vladimir M
  • 4,403
  • 1
  • 19
  • 24
0

Just do what you want to do when the result is there, i.e. execute the code that needs the result from within the callback function:

var reader = new window.FileReader();
reader.readAsDataURL(array); 
reader.onloadend = kk= processResult;


function processResult() {
    var base64data = reader.result;
    // all processing should come here or be launched from here.
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • you would need to make sure you return something in that processResult() function, right? – Brandon Oct 11 '16 at 18:39
  • @James No, you don't `return` anything from asynchronous callbacks unless you're in a promise chain – Bergi Oct 11 '16 at 18:40
  • Usually it's better to add the load events before reading, just in case the read happens synchronously. – Oriol Oct 11 '16 at 18:51