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?

2
  • You’re not using await in an async function. Commented Dec 24, 2021 at 15:01
  • Avoid the Promise constructor antipattern in $api! Commented Dec 25, 2021 at 2:18

1 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.