1

I'm pretty new to javascript and have been looking through guides to how to correct issues that come from asynchronous behavior, but this case doesn't seem to be solved by using closure in a function. All I need to do is access a value that is correctly set inside an asynchronous function after it's completed, but no matter what kind of variable I assign to the set value, it returns to its original value (undefined) outside of the asynchronous functions scope.

function callbackClosure(i, callback) {
    return function () {
        return callback(i);
    };
}

var base64data;
var reader = new FileReader();

reader.readAsDataURL(e.data);
reader.onloadend = function () {
    base64data = reader.result;
    base64data = base64data.split(",")[1];
    alert("0: " + base64data);    //base64data is correct here    
};                    
alert("1: " + base64data);   //base64data value needs to be set correctly at this point, but it's undefined
$.ajax({
    cache: false,
    url: _w.emailConfirmationReportsUrl +'?mapData="' + base64data + '"'
});

It's frustrating because base64data's value is clearly correct at the first alert 0, which is called first, but it's undefined again at alert 1. I can't use ajax in the onloadend function either for some reason. Can anyone explain what's going on between alert 0 and alert 1 that would cause base64data to lose the value it was set to? I've tried using the callbackClosure function in a number of different places on pretty much every function that's used, but it hasn't changed the behavior.

PgM
  • 11
  • 1
  • `onloadend` is being defined at that point in your code, but it's not finishing until a point in the future, *after* you're attempting to use its values. Put your `alert("1...` and your `$.ajax` call inside the `onloadend` function. What do you mean by "I can't use ajax in the onloadend function"? – Charlie Schliesser Nov 30 '18 at 15:48
  • For some reason it just doesn't trigger the method inside the controller, I've changed a few things since I last attempted though so I'll give it another shot. Thanks for your help! – PgM Nov 30 '18 at 16:02
  • Okay, so the real issue appears to be that I can't call the ajax from this asynchronous function in the code. It just doesn't reach the controller and I'm not sure why... Do you have any idea why that might be the case? – PgM Nov 30 '18 at 17:34

0 Answers0