开发者问题收集

Vue js-异步等待问题

2021-12-24
432

我在 Login.Vue 中的代码如下

methods: {
            async validateLoginBeforeSubmit () {
                this.$validator.validate().then((result) => {
                    if (result) {
                        var data = {
                            email: this.email,
                            password: this.password
                        }
                        var response =  await this.$api('POST', 'login', data);
                    }
                })
            },
        },

这是原型函数

import Vue from 'vue';

Vue.prototype.$api = async() => function(method, url, data){
    if (method == 'POST') {
      return new Promise((resolve) => {
        this.$http.post(url, data).then((response) => {
          resolve(response);
        }).catch((error) => {
          if (error.response.status == '401') {
            /* Destroy token from local storage and redirect to login page */
          }
          resolve(error.response);
          return false;
      });
    });
  }
}

它引发以下错误

error  Parsing error: Unexpected reserved word 'await'.

有人可以帮助我吗?

1个回答

您不应混合搭配 async/await 和传统的 then 承诺处理,因为这会造成混淆。

Insted try:

async validateLoginBeforeSubmit () {
  var result = await this.$validator.validate()
  if (result) {
    var data = {
      email: this.email,
      password: this.password
    }
    var response = await this.$api('POST', 'login', data);
  }
}
match
2021-12-24