sweetalert2 example reports: await is only valid in async functions and async generators
Andrew Henderson
I use sweetalert2 for some dialogs in my application. However, the the sweetalert2 website provides some examples that reported this error when I literally copy/pasted them in my webapplication code:
SyntaxError: await is only valid in async functions and async generators
After some research I added async before function testSweetalert(). Although this did solve the syntax error, the code does neither reach the statement resolve('You need to select Ukraine :)') or swal('You selected: ' + country).
The Javascript code below is called in my html code like this:
<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) } }Although I tried to learn more about async functions and using Promise I can't figure out what is wrong with the above code. This is specifically confusing me because the code examples I found on sweetalert2 work fine on their github page.
3 Answers
Try this:
(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)
}
})()Reference: INPUT TYPE SELECT WITH SWEETALERT2
0The error speaks for itself. You can use await only in async functions. Simply put the keyword "async" in front of the function. See below:
(async () => {
//your function
})() 0 As far as I know now you need add
await swal.fire({ 0