我编写了一个 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 now
显示在Not a proper file Fasta file
之前并且函数总是向调用者函数返回 true 为什么会这样?我该如何解决这个问题?
最佳答案
FileReader
异步执行。这意味着在读取文件时,代码继续执行并触发第二个警报
。要停止此行为,请将所有依赖于文件读取器的代码放置在 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!");
}
请注意,您无法从异步处理程序返回。相反,您需要在异步函数完成后调用一个函数来处理结果。
关于JavaScript 函数无法正确返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27899982/