Waiting for a file to load (onload JavaScript)
28,878
Of course the alert isn't in the onload function, so it's called immediately.
You may do that :
var val = "x";
//... code to load a file variable
var r;
r = new FileReader();
r.onload = function (e) {
val = e.target.result;
r.readAsText(file);
alert(val);
};
You cannot wait and stop the execution of your code, so the general idea is to defer it using a callback.
Supposing the code you show is really to be done in two parts, one doing file manipulation and the other one using it, it could be like this :
function fetchVal(callback) {
var val = "x";
//... code to load a file variable
var r;
r = new FileReader();
r.onload = function (e) {
val = e.target.result;
r.readAsText(file);
callback(val);
};
}
fetchVal(function(val){
alert(val);
// use val
});
Author by
krajol
Updated on December 07, 2020Comments
-
krajol over 3 years
I want to read a text from a file and return it in a function. So here's the important part of my code:
function getFileRequest(id, contentType, callback) { var val = "x"; if (window.File && window.FileReader && window.FileList && window.Blob) { var element = document.getElementById(id); var file = element.files[0]; if(file != null) { if(file.type.match("text/xml")){ var r; r = new FileReader(); r.onload = function (e) { val = e.target.result; } r.readAsText(file); } else alert("Wrong file format"); } } else { alert('The File APIs are not fully supported by your browser.'); } alert(val); if(val == null) return ""; else return getRequestBody(id,contentType,val); }
I want to pass the text to a variable called "val". But, as it seems to me at least, alert(val) is always showing default "x" because probably it's not waiting for onload function to be executed. Am I right at all? How can I get an access to that text then? Is there a way to wait for an excecution?