如何在 promise 中使用 async/await - Vue [英] How to use async/await inside promise - Vue

查看:90
本文介绍了如何在 promise 中使用 async/await - Vue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的方法:

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

我在 isActive = true 时显示加载器,但是在 this.$validator 中使用 await 会抛出一个关于 word <的错误code>await 是保留的.对于验证,我使用 VeeValidate

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

如何在 $validator 承诺中使用 await?

How can i use await inside $validator promise?

推荐答案

您不能在非异步函数中直接使用 await 关键字.您在匿名函数中直接使用 await 关键字,它是 then 的参数;这个匿名函数不是async,所以你有一个语法错误.

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

我发现当您已经在 async 函数中时,避免使用 then 更简洁.

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

顺便说一句,我不确定您的 data 变量是在哪里定义的.

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

这篇关于如何在 promise 中使用 async/await - Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆