我在我的应用程序中使用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页面上运行良好。
据我所知,你需要添加
await swal.fire({