I'm having a real hard time figuring out the behaviour of Promises
. I'm using Vue
and the vee-validate
library, which allows for manual validation of a form via:
this.$validator.validate()
However, when I try to use it I get weird behaviour:
async isFormValid() {
return await this.$validator.validate();
},
Whenever I submit a form with errors, the form sends the AJAX request:
onApprove() {
if (!that.isFormValid) {
return false;
}
$.ajax({
...
});
return false; // Modal never closes unless AJAX is successful.
},
Additionally, I've tried the following construct:
onApprove() {
this.$validator.validate().then(result => {
if(result) {
$.ajax({
...
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
But this doesn't work either. I've found a work-around by doing this:
isFormValid() {
this.$validator.validate();
return Object.keys(this.fields).every(key => this.fields[key].valid);
},
But if someone could explain what I'm misunderstanding about the `Promise, that would be great.
Edit
Full onApprove example (always returns true regardless of validation:
onApprove() {
that.$validator.validate().then(result => {
if (result) {
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
}
return false; // Modal never closes unless AJAX is successful.
});
},
This method also doesn't work (return false first):
onApprove() {
that.$validator.validate().then(result => {
if (!result) {
return false
}
$.ajax({
url: '/settings/user_management_add_user', method: 'POST', data: {
csrfmiddlewaretoken: that.csrfToken, password: that.password, user: JSON.stringify(that.users[that.activeUserRow]),
}, success() {
$('#modify_user_modal').modal('hide');
that.showToast('check icon', gettext('User created'));
that.activeUserRow = undefined;
that.initialQuery();
}, error(data) {
that.showToast('remove icon', gettext('User could not be created'));
if (data.responseText && data.responseText.length < 20) {
that.showToast('remove icon', data.responseText);
}
},
});
return false; // Modal never closes unless AJAX is successful.
});
},