I’ve been trying to implement SweetAlert2, and after trying for hours to figure out how to stop an inline flow from proceeding until my JavaScript function had finished, and reading somewhere here that all steps are essentially promises, I’ve finally sorted my code out.
However, not being all that familiar with Promises (more async/await here), I’d like to know if the below is actually decent code, or whether it’s a hodgepodge that somehow works.
Do you actually have any “await” in the Run Javascript step?
Because “return new Promise” doesn’t actually return false/true, it actually returns a Promise object, which is eventually “transformed” to the actual false or true.
So, in theory, you need to have a “await” somewhere to wait for the Promise to transform itself into an actual boolean, otherwise you might be doing the comparison “Promise === true” instead of “true === true” or “false === true”
Edit: I’m not familiar with Wappler inline flows, maybe they’re internally awaiting the Promise already, so that’s why it’s working
In that case, it’s safe to assume confirmedcallback and denycallback are not Promises (or they’ve already been “transformed” by Wappler awaiting them), so they can be used directly in the if conditions.
Everything looks good to me
Edit: The alternative to promises, would be doing something like:
let result = await Swal.fire(...) // Swal.fire returns a Promise, you use await to wait for it to "transform" itself
if (result.isConfirmed && confirmedcallback) {
// ...
// Don't put resolve(true), use return true
} else if (result.isDenied && denycallback) {
// ...
// Don't put resolve(false), use return false
}
Async/await is the evolution of Promises, so you don’t have to carry around with .then()
Edit 2: To use await, the function needs to start with “async function”
So the confirmedcallback and denycallback have been axed. I've set it a different way as to whether I want that second alert/confirm box after confirming or denying. Promises will always be sent back, because Wappler is waiting for it.
}).then((result) => {
if (result.isConfirmed) {
if (confirmationdialog) {
Swal.fire('Saved!', '', 'success');
}
resolve(true);
} else if (result.isDenied) {
if (denydialog) {
Swal.fire('Changes are not saved', '', 'info');
}
resolve(false);
}
})
That's correct. That's why I did some digging how to return a Promise another way and found this solution.
Thanks for your feedback @Apple, good to see I'm on the right path. Always learning new ways around things.
Since you use it in the browser it is best to use the Promise like you do instead of async/await, with Promises you will have more browser coverage. The code looks good, that is how I also would have done it.