2015-01-12 34 views
0

我已經寫了一個javascript函數來驗證文件輸入文件: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; 
    } 
} 

在我的表單提交的代碼,我調用這個函數來檢查文件validation.Function正確作爲工作我可以從函數獲取警報消息,但在Not a proper file Fasta file之前顯示提示消息VAlidate function to end now,並且函數始終返回true以致調用函數爲什麼這樣?我該如何解決這個問題?

回答

1

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

請注意,你不能從一個異步處理程序返回。相反,您需要調用一個函數來處理異步函數完成後的結果。

+0

謝謝你向我解釋原因,它真的爲我清除了理由,但是當我在這種情況下嘗試相同的代碼時,它返回undefined。 –

+0

沒問題,看我的更新 –