我使用 sweetalert2 对于我的应用程序中的一些对话框。然而,sweetalert2 website提供了一些当我将其复制/粘贴到我的 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>
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上工作得很好页。
最佳答案
试试这个:
(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)
}
})()
关于javascript - sweetalert2 示例报告 : await is only valid in async functions and async generators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942149/