Home > Back-end >  Vue js - async await issue
Vue js - async await issue

Time:12-25

My Code in Login.Vue is as below

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);
                    }
                })
            },
        },

and this is the prototype function

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;
      });
    });
  }
}

It is throwing below error

error  Parsing error: Unexpected reserved word 'await'.

Can anyone help me for the same?

CodePudding user response:

You shouldn't mix and match async/await and traditional then promise handling as it can cause confusion.

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);
  }
}
  • Related