开发者问题收集

Vue.js。async/await 未按预期工作

2018-11-03
443

即使此方法似乎运行正确,控制台日志也显示最终结果在内置 await/sync 之前输出

    submitForm: function() {
      console.log("SUBMIT !");
      // vee-validate form validation request
      const makeValidationRequest = () => {
        return this.$validator.validateAll();
      };
      const validateAndSend = async () => {
        const isValid = await makeValidationRequest();
        console.log("form validated... isValid: ", isValid);
        if (isValid) {
          console.log("VALID FORM");
          // axios post request parameters
          const data = { ... }
          };
          const axiosConfig = {
            headers: { ... }
          };
          const contactAxiosUrl = "...";
          // send axios post request
          const makeAxiosPostRequest = async (url, data, config) => {
            try {
              const result = await axios.post(url, data, config);
              console.log("axios post request result: ", result);
              return true;
            } catch (err) {
              console.log("axios post request: ", err.message);
              return false;
            }
          };
          this.$store.dispatch("switchLoading", true);
          const sent = await makeAxiosPostRequest( contactAxiosUrl, contactAxiosData, axiosConfig );
          this.$store.dispatch("switchLoading", false);
          return sent;
        } else {
          console.log("INVALID FORM");
          return false;
        }
      };
      const result = validateAndSend();
      console.log("RESULT: ", result);
    },

the console log is :

    SUBMIT !
    app.js:3312 RESULT:  Promise {<pending>}__proto__: Promisecatch: ƒ catch()constructor: ƒ Promise()finally: ƒ finally()then: ƒ then()arguments: (...)caller: (...)length: 2name: "then"__proto__: ƒ ()[[Scopes]]: Scopes[0]Symbol(Symbol.toStringTag): "Promise"__proto__: Object[[PromiseStatus]]: "resolved"[[PromiseValue]]: false
    app.js:3209 form validated... isValid:  false
    app.js:3291 INVALID FORM

我通常应该得到:

 SUBMIT !
 form validated... isValid:  false
 INVALID FORM

最后

 RESULT

我的嵌套 awaut/sync 有什么问题... 感谢您的反馈

2个回答

validateAndSend 立即返回承诺。

将:

const result = validateAndSend(); 

更改为:

const result = await validateAndSend(); 

(并将 async 添加到 submitForm)

等待承诺完成后再记录结果。

Bob Fanger
2018-11-03

删除 makeValidationRequest 函数,它是不必要的,也是错误的。试试这个:

submitForm: async function () {
  // get form validation status
  let formIsValid = await this.$validator.validateAll()

  let url = ''
  let formData = {}
  let config = {
    headers: {}
  }

  const postData = async (url, dta, cnf) => {
    try {
      // first, show loader
      this.$store.dispatch('switchLoading', true)
      // then try to get response.data
      let {data} = await axios.post(url, dta, cnf)
      // if successful, just console it
      console.log(`form post successful: ${data}`)
    } catch (err) {
      // if unsuccessful, console it too
      console.log(`error posting data: ${err}`)
    } finally {
      // successful or not, always hide loader
      this.$store.dispatch('switchLoading', false)
    }
  }

  formIsValid && postData(url, formData, config)
  // else not required, you can't submit invalid form
}
Vladislav Ladicky
2018-11-03