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.