I have this code
function gotFile(file){
readAsText(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function() {
var string = evt.target.result;
};
alert(string) // returns null
reader.readAsText(file);
}
Apparently I'm trying to get result from asynchronous callback in synchronous function and that's not possible.
So I've changed my code like this :
function gotFile(file){
readAsText(file,function(str){
return str;
});
}
function readAsText(file,callback) {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsText(file);
alert(callback);
}
returns me the string
function(str){
return str;
}
How can I achieve this ?
Thank you
In your updated version you are still trying to use an asynchronous operation as if it were synchronous.
In the callback function, returning the str value is pointless. You need to do something with the str value instead, right there inside callback (or in another function that you call from callback).
For example:
function gotFile(file){
readAsText(file,function(str){
alert(str);
});
}
function readAsText(file,callback) {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
};
reader.readAsText(file);
}
Note the difference: Instead of returning str from callback, we do something with str (call the alert function) right there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With