简体   繁体   English

使用 async 和 await 返回解析错误

[英]Using async and await returns parsing error

I have this function that uses validate from yup and it has async function in it.我有这个 function ,它使用来自 yup 的验证,它有异步 function 。 If I want to use the whole function how can I wait for it to finish here is code如果我想使用整个 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);
    }
  };

I want to wait for the first sentence to finish which is我想等待第一句话说完

companyRef.handleProfileFormSubmit();

the async function is here异步 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();
        }
      });
  };

How can I do this?我怎样才能做到这一点?

You're mixing concerns by putting your validation and submit handler into one, but it's still possible (and fine, extract stuff into functions to make it less complicated).您通过将验证和提交处理程序合二为一来混合关注点,但这仍然是可能的(很好,将内容提取到函数中以使其不那么复杂)。

Below example shows where to handle validation errors and submission errors (if submission is async, which it usually is):下面的示例显示了在哪里处理验证错误和提交错误(如果提交是异步的,通常是这样):

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM