iep*_*iep 4 javascript asynchronous sweetalert2
我在应用程序中的某些对话框中使用了sweetalert2。但是,sweetalert2 网站提供了一些示例,当我将它们复制/粘贴到我的 Web 应用程序代码中时,这些示例报告了此错误:
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>
Run Code Online (Sandbox Code Playgroud)
<button onclick="testSweetalert()">test</button>
Run Code Online (Sandbox Code Playgroud)
尽管我试图了解有关async
函数和使用的更多信息,但Promise
我无法弄清楚上述代码有什么问题。这让我特别困惑,因为我在sweetalert2上找到的代码示例在他们的github页面上运行良好。
尝试这个:
(async () => {
const {value: country} = await swal.fire({
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.fire('You selected: ' + country)
}
})()
Run Code Online (Sandbox Code Playgroud)
参考: INPUT TYPE SELECT WITH SWEETALERT2