Stop the control while SweetAlert is on screen [du

2020-04-13 05:58发布

问题:

I am using sweetalert2 library for showing alert in my code.

ConfirmationMessage = function(msg) {
    swal({
            title: "",
            text: msg,
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Ok",
            cancelButtonText: "Cancel",
            closeOnConfirm: false,
            closeOnCancel: false,
            allowEscapeKey: true

        });
}

This is the JS function and I am using it at other place.

if (!ConfirmationMessage("message to show.")) {
    alert("if");           
}
else {
    alert("else");
}

My issue is

I want to stop the control when the alert is on screen and want to decide on the button push if OK come to If Condition if Cancel come to else condition but control does not wait for the response in sweetalert2.

回答1:

Creating the swal is an asynchronous process, meaning you cannot just return a synchronous result from it.

If you look at the docs, you can see that swal returns a promise, so you can take advantage of that and pass the success and fail callbacks:

ConfirmationMessage = function(msg) {
  return swal({ ... }); // <--- return the swal call which returns a promise
};

ConfirmationMessage('message to show')
  .then(function() {
    // success happened
  }, function(dismiss) {
    // fail happened
    // dismiss can be 'cancel', 'overlay', 'close', and 'timer'
    if (dismiss === 'cancel') {
      // user cancelled
    }
  });