Using window.confirm as a Promise
When writing a modern JavaScript application that uses Promises or async/await, it is sometimes useful to wrap other things in promises so they can more easily be used in a standard way throughout your codebase or in promise chains.
This is especially true if a built-in feature has the same properties of a promise, but is not one. The window.confirm
API is one that I wrap a lot in my applications:
function confirmDialog(msg) { return new Promise(function (resolve, reject) { let confirmed = window.confirm(msg); return confirmed ? resolve(true) : reject(false); }); }
And now we can use it just like a normal promise:
confirmDialog('Do you really want to delete this?') .then(() => doYourDeleteAction(task.id)) .catch(err => alert('Unable to delete!'))
Now if you ever want to replace that confirm dialog with some custom version with a fancy UI like a modal window, you can do so much easier – just by updating the confirmDialog
function itself.
Categories: Programming, Software