Javascript 函数无法正确返回

Javascript function does't return properly

本文关键字:返回 函数 Javascript      更新时间:2023-09-26

我写了一个javascript函数来验证文件输入文件:

function valaidateform() {
    var fileInput = document.getElementById('file');        
    message = "";
    var file = fileInput.files[0];
    var textType = /text.*/;    
    if (file.type.match(textType)) {
        var reader = new FileReader();                  
        reader.onload = function(e) {
            filecontent =  reader.result.trim();
            var res = filecontent.split("'n");          
            lines = res.length;
            if (!(filecontent.substring(0, 1) == ">")) {
                alert("Not a proper file Fasta file");   
                return false;
            }
        }
        reader.readAsText(file);    
    } 
    else {
        alert("File not supported!");
    }
    alert("VAlidate function to end now")               
    return true;
}
//On form submit I call validateform() function
formrequest.submit(function() { 
    alert(valaidateform());
    if (validationstatus == false) {
        return false;
    }
}

在我的表单提交代码上,我调用此函数来检查文件验证。函数工作正常,因为我可以从函数中获取警报消息,但警报消息VAlidate function to end nowNot a proper file Fasta file之前显示,并且函数始终返回 true 给调用方函数 为什么会这样?我该如何解决这个问题?

FileReader异步

执行。这意味着在读取文件时,代码执行将继续并命中您的第二个alert。若要停止此行为,请将依赖于文件读取器的所有代码放在onload处理程序中:

if (file.type.match(textType)) {
    var reader = new FileReader();                  
    reader.onload = function(e) {
        filecontent =  reader.result.trim();
        var res = filecontent.split("'n");          
        lines = res.length;
        if (!(filecontent.substring(0, 1) == ">")) {
            alert("Not a proper file Fasta file");   
        }
        alert("Validate function to end now") // note success alert placed here         
        // call a function here which handles the valid file result
    }
    reader.readAsText(file);    
} 
else {
    alert("File not supported!");
}

请注意,不能从异步处理程序返回。相反,您需要在异步函数完成后调用一个函数来处理结果。