Search code examples
javascriptsweetalert2

How to rewrite swal prompt without using promises


I want to have a prompt option for my alert before deleting an item. However it does not work in IE. How can I avoid using this promise (.then()) ?

The example from swal is this:

swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this imaginary file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
    swal("Poof! Your imaginary file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your imaginary file is safe!");
  }
});

Solution

  • Assuming that the rest of swal works on IE (have you checked?), then you'll need to:

    1. Add a Promise polyfill, of which there are many easily come by, and

    2. Not use arrow functions, since arrow functions aren't supported by IE

    For instance, with a Promise polyfill, this is valid code for IE:

    swal({
      title: "Are you sure?",
      text: "Once deleted, you will not be able to recover this imaginary file!",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    })
    .then(function(willDelete) { // <=== Only change is here
      if (willDelete) {
        swal("Poof! Your imaginary file has been deleted!", {
          icon: "success",
        });
      } else {
        swal("Your imaginary file is safe!");
      }
    });
    

    Or you can use a tool like Babel that transpiles ES2015+ code to be ES5-compatible and can optionally include polyfills (for things like Promise). Babel would handle converting arrow functions for you.