0

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?

Ronak Solanki
  • 39
  • 1
  • 8
  • You’re not using await in an async function. – Terry Dec 24 '21 at 15:01
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it) in `$api`! – Bergi Dec 25 '21 at 02:18

1 Answers1

2

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);
  }
}
match
  • 10,388
  • 3
  • 23
  • 41
  • @match- Your solution works at all, amazing Now i have one small question What if i don't want to return anything if catch block execute from the Vue.prototype.$api function and just alert there and return false? – Ronak Solanki Dec 24 '21 at 15:05