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?
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
});
                        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