且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 promise 中使用 async/await - Vue

更新时间:2023-10-25 15:25:04

您不能在非异步函数中直接使用 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.