【发布时间】:2023-04-07 09:31:01
【问题描述】:
它不等待验证,只需运行 else 部分:|我的错在哪里?
async validateBeforeSubmit(event) {
await this.$validator.validateAll().then( result => {
if (result) {
console.log(result); // just log the -> true
// go submit
}else{
console.log(result); // just log the -> false
event.preventDefault();
var elmnt = document.getElementById("drop_zone");
elmnt.scrollIntoView();
}
})
.catch(error=>console.log(error));
},
我正在使用 veevalidator,我定义了一些需要几秒钟才能解决的自定义规则:
created() {
this.$validator.extend('unique', {
// getMessage: field => 'At least one ' + field + ' needs to be checked.',
async validate(value, arg) {
arg = arg[0];
let sw = false;
if (arg == 'n_code') {
let data = {
'n_code': value
}
await Axios.post(duplicate_ncode, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'email') {
let data = {
'email': value
}
await Axios.post(duplicate_email, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
if (arg == 'mobile') {
let data = {
'mobile': value
}
await Axios.post(duplicate_mobile, data, {
headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') }
})
.then((response) => {
if (response.data == true) {
sw = true;
}
})
.catch(error => console.log(error));
if (sw) {
return true;
} else {
return false;
}
}
// console.log('questions', value, testProp, options.some((option) => option[testProp]));
// return true;
}
});
}
当用户填写所有字段时,它将检查 3 个 api 并且需要 momnets 来检查。 我需要等待才能得到答案,但是有一些错误是行不通的。
请帮忙
【问题讨论】:
-
您使用了两种不同的模式。异步和等待,以及事件链回调。
-
什么是
this.$validator?如果它真的返回了一个承诺,那么这段代码应该等待承诺所代表的一切完成后再继续。 (这不是惯用的,正如@CodeMonkeyForHire 指出的那样,但是您上面所拥有的应该工作。只是FWIW,this 将是惯用的版本,假设validateBeforeSubmit绝不应该允许其承诺被拒绝[就像你上面的代码]。) -
如果您现在运行它,控制台中显示的实际消息是什么?
-
表单将提交并且不显示任何内容,因为它不会等待响应,但如果我使用 event.preventDefault();在顶部停止提交,它将在 3 秒后显示验证结果,如果验证为真,则为真,如果验证为假,则为假。
标签: javascript vue.js async-await