等待文件加载(onload JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12090996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:05:07  来源:igfitidea点击:

Waiting for a file to load (onload JavaScript)

javascriptfileonloadwaitfilereader

提问by krajol

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?

我想将文本传递给一个名为“val”的变量。但是,至少在我看来,alert(val) 总是显示默认的“x”,因为它可能没有等待执行 onload 函数。我完全正确吗?那么我如何才能访问该文本?有没有办法等待执行?

回答by Denys Séguret

Of course the alert isn't in the onload function, so it's called immediately.

当然,警报不在 onload 函数中,因此会立即调用。

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