Search code examples
vuejs2laravel-mixsweetalert2

How to resolve: "Can not use keyword 'await' outside an async function"


Inside my Vue Component. I have a method (show) that shows sweetalert2 input message. But it returns an error after using 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)
    }
}

The error is:

Can not use keyword 'await' outside an async function


Solution

  • I'm unsure exactly the calling syntax you have for the show method, but you need to declare that function as async in order to use await.

    For example, in a module method:

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

    As an instance method in a class:

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