[英]Using async and await returns parsing error
我有這個 function ,它使用來自 yup 的驗證,它有異步 function 。 如果我想使用整個 function 我怎么能等待它完成這里是代碼
const handleSubmit = () => {
companyRef.handleProfileFormSubmit();
setModal(true);
setIsSubmitting(true);
console.log(companyRef.handleFocusOnError());
if (!companyRef.handleFocusOnError() && !isButtonValid) {
console.log('first if in handlesubmut', companyRef.handleFocusOnError());
handleBankDetailsClick();
}
if (isButtonValid && !companyRef.handleFocusOnError()) {
bankRef.handleBankFormSubmit();
history.push(DASHBOARD);
} else if (isButtonValid && companyRef.handleFocusOnError()) {
setIsBankDetailsOpen(true);
}
};
我想等待第一句話說完
companyRef.handleProfileFormSubmit();
異步 function 在這里
handleProfileFormSubmit = () => {
const { profile } = this.state;
const { errorValues } = this.state;
let errorExists = false;
let urls = url.format(profile.website.value);
if (!startsWith(urls, 'http://') && !isEmpty(urls)) {
urls = 'http://' + urls;
}
console.log(urls);
this.schema
.validate(
{
name: profile.name.value,
industry: profile.industry.value,
address: profile.address.value,
crn: profile.crn.value,
website: urls,
employeesNbr: profile.employeesNbr.value,
phoneNumber: profile.phoneNumber.value,
userRole: profile.userRole.value,
personCheck: profile.personCheck.value,
},
{ abortEarly: false },
)
.catch(err => {
errorExists = true;
const errors = {};
for (const i of err.inner) {
errors[i.path] = i.message;
}
const sortedErrors = Object.keys(errors);
sortedErrors.forEach(key => {
profile[key].hasError = true;
profile[key].errorMessage = errors[key];
errorValues.inputErrors.value.push(key);
this.setState({ errorValues });
});
})
.then(() => {
console.log('while submitting', errorValues);
this.handleModalError();
if (errorExists) {
this.props.handleCompanyError();
}
});
};
我怎樣才能做到這一點?
您通過將驗證和提交處理程序合二為一來混合關注點,但這仍然是可能的(很好,將內容提取到函數中以使其不那么復雜)。
下面的示例顯示了在哪里處理驗證錯誤和提交錯誤(如果提交是異步的,通常是這樣):
handleProfileFormSubmit = async () => {
try {
await this.schema.validate({...});
// now you know your form is valid - move on to submission
try {
await processSubmission(...);
// submission successful!
} catch(err) {
// error occurred while submitting
}
} catch(err) {
// error occurred while validating
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.