sweetalert2示例报告:await仅在异步函数和异步生成器中有效

问题描述 投票:3回答:1

我在我的应用程序中使用sweetalert2作为一些对话框。但是,当我在webapplication代码中复制/粘贴它们时,sweetalert2 website提供了一些报告此错误的示例:

SyntaxError: await is only valid in async functions and async generators

经过一些研究后,我在async之前添加了function testSweetalert()。虽然这确实解决了语法错误,但代码既未达到语句resolve('You need to select Ukraine :)')swal('You selected: ' + country)

下面的Javascript代码在我的html代码中调用,如下所示:

<button onclick="testSweetalert()">test</button>
async function testSweetalert() {

  const {value: country} = await swal({
       title: 'Select Ukraine',
       input: 'select',
       inputOptions: {
                'SRB': 'Serbia',
                'UKR': 'Ukraine',
                'HRV': 'Croatia'
       },
       inputPlaceholder: 'Select country',
       showCancelButton: true,
       inputValidator: (value) => {
        return new Promise((resolve) => {
          if (value === 'UKR') {
            resolve()
          } else {
            resolve('You need to select Ukraine :)')
          }
        })
       }
    })
    if (country) {
            swal('You selected: ' + country)
    }
 }

虽然我试图了解更多有关async函数和使用Promise的信息,但我无法弄清楚上面的代码有什么问题。这特别让我感到困惑,因为我在sweetalert2上找到的代码示例在他们的github页面上运行良好。

javascript asynchronous sweetalert2
1个回答
-1
投票

据我所知,你需要添加

await swal.fire({
© www.soinside.com 2019 - 2024. All rights reserved.