I have the following typescript code:
var base;
readFile(file, function(e) {
base = e.target.result;
});
alert(base);
The variable "base" gets its value inside the readFile function, and if I do an alert() inside readFile I can see its value without any problem, but if I want to see the value of "base" outside the readFile function it returns undefined .
How can I make the base variable hold the assigned value outside of the readFile function?
Here I also leave the content of the readFile function, which works perfectly:
function readFile(file, onLoadCallback){
var reader = new FileReader();
reader.onload = onLoadCallback;
reader.readAsText(file);
}
I solved the problem following the indications that they gave me, in the following way:
In this way the execution of the callback function is done and then I can return the value. Then I decode the "base" object and voila, I get the base64 string I wanted.
It doesn't lose value, it's just being used before you have it.
That's because the function
readAsText()
reads the file asynchronously so a callback function is passed that will be executed when the read is doneonload
.The execution sequence would be like this:
The value of
base
is available until the callback function is executed.