Waiting for a file to load (onload JavaScript)

那年仲夏 提交于 2019-12-24 10:00:02

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/12090996/waiting-for-a-file-to-load-onload-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!