I use JS FileReader. I want to get result after file reading operation and work with this data. FileReader is asynchronous and I don’t know when result is ready. How to get it done right?
$(document).ready(function(){
$('#file_input').on('change', function(e){
var res = readFile(this.files[0]);
//my some manipulate with res
$('#output_field').text(res);
});
});
function readFile(file){
var reader = new FileReader(),
result = 'empty';
reader.onload = function(e)
{
result = e.target.result;
};
reader.readAsText(file);
//waiting until result is empty?
return result;
}
It’s show “empty”.
How to wait until “result” is empty?
Another way?
Reading happens asynchronously. You need to provide a custom
onloadcallback that defines what should happen when the read completes:(See the Fiddle.)
Note that
readFiledoes not return a value. Instead, it accepts a callback function, which will fire whenever the read is done. The$('#output_field').textoperation is moved into the callback function. This ensures that that operation will not run until the reader’sonloadcallback fires, whene.target.resultwill be filled.Programming with callbacks is a bit difficult to get right at first, but it is absolutely necessary for implementing advanced functionality.