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(
  .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.

Don’t Bet Against Language Features

Remember when all the blogs in PHP land were telling you to use single quotes because double quotes are slow? I was a heavy PHP user at the time, and man I sure do. The advice was actually factually correct at the time, but has long been fixed in PHP, and it would never have mattered in your application anyways. I have seen this scenario play out again – this time with JavaScript Promises.

Be wary anytime you hear something along the lines of “use X instead of Y, because Y is slow” – where Y is a built-in programming language feature. This argument crops up from time to time, but it is almost always a complete non-issue in the long run. Continue reading