Abhijeet Panwar
Abhijeet Panwar

Reputation: 1867

Javascript function does't return properly

I have written a javascript function to validate a file input file :

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

On my form submit code I call this function to check for file validation.Function is working properly as I can get alert message from function but alert message VAlidate function to end now is shown before Not a proper file Fasta file and function always return true to caller function Why so? How can I resolve this?

Upvotes: 0

Views: 64

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337743

The FileReader executes asynchronously. This means that while the file is being read code execution continues on and hits your second alert. To stop this behaviour place all code reliant on the file reader within the onload handler:

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

Note that you cannot return from an async handler. Instead you need to call a function to handle the result once the async function has completed.

Upvotes: 1

Related Questions