0

Here's my method:

async sendEmail() {
  this.isActive = true
  this.$validator.validate().then(result => {
    if (result) {
      await axios.post('url', data)
      this.isActive = false
    }
  })
}

I'm showing the loader when isActive = true, but using await inside this.$validator throw me an error about word await is reserved. For validation i use VeeValidate

How can i use await inside $validator promise?

Alexander Kim
  • 17,304
  • 23
  • 100
  • 157
  • You can use `await` only inside an `async` function. So, try changing it to: `this.$validator.validate().then(async (result) =>{}` – adiga Dec 25 '18 at 09:39
  • @adiga, no error, but it doesn't work as intended, it should set `isActive` to false, after axios request, but `isActive` is always true. – Alexander Kim Dec 25 '18 at 09:46

1 Answers1

4

You can't use the await keyword directly inside a function that isn't async. You are using the await keyword directly inside the anonymous function which is then's parameter; this anonymous function isn't async, so you have a syntax error.

Here's how I would rewrite this function:

async sendEmail() {
  this.isActive = true
  let result = await this.$validator.validate();
  if (result) await axios.post('url', data);
  this.isActive = false;
}

I find it's cleaner to avoid using then when you're already inside an async function.

Btw, I'm not sure where your data variable is defined.

Gershom Maes
  • 7,358
  • 2
  • 35
  • 55
  • `data` is defined, there's no problem with it. Now it works, thanks. Btw, is it ok to use `try {} catch {}` inside `async` functions? e.g. `if (result) { try { ... } catch {...} }` – Alexander Kim Dec 25 '18 at 09:56
  • Yes `try` and `catch` will work exactly as you would expect them to! – Gershom Maes Dec 25 '18 at 20:18