首页 > 解决方案 > 如何解决:“不能在异步函数之外使用关键字‘await’”

问题描述

在我的 Vue 组件中。我有一个显示 sweetalert2 输入消息的方法(显示)。但是使用 laravel mix (npm run watch) 后返回错误

show(){

    const { value: email } = await Swal.fire({
    title: 'Input email address',
    input: 'email',
    inputPlaceholder: 'Enter your email address'
    })

    if (email) {
        Swal.fire('Entered email: ' + email)
    }
}

错误是:

不能在异步函数之外使用关键字“等待”

标签: vuejs2laravel-mixsweetalert2

解决方案


我不确定你对 show 方法的调用语法,但你需要声明该函数async才能使用await.

例如,在模块方法中:

const show = async () => {
  const { value: email } = await Swal.fire({
    title: 'Input email address',
    input: 'email',
    inputPlaceholder: 'Enter your email address'
  })

  if (email) {
    Swal.fire('Entered email: ' + email)
  }
}

作为类中的实例方法:

class MyComponent {
  async show() {
    const { value: email } = await Swal.fire({
      title: 'Input email address',
      input: 'email',
      inputPlaceholder: 'Enter your email address'
    })

    if (email) {
      Swal.fire('Entered email: ' + email)
    }
  }
}

推荐阅读