未使用(承诺)取消使用SweetAlert2

时间:2016-09-04 21:24:12

标签: javascript jquery ajax sweetalert sweetalert2

如何在使用promises时正确转义取消按钮而不会抛出错误?我的代码会抛出一个带有必填复选框的警报确认。代码应该对用户执行,但它会在控制台窗口中抛出错误:

  

未捕获(承诺)取消

//validation logic all passes...Now proceed to...

 else
    {

//determine and parse Discounts

 var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
  .done(function(json_data){
     var theResponse1 = $.parseJSON(json_data);
     myDiscountRate = theResponse1['ourDiscountFound'];

    }).then( function(callback){

    priceRate = priceRate * (1 - (.01 * myDiscountRate));
    newRate = priceRate.toFixed(2);
}

swal({
  title: "Confirm",
  input: 'checkbox',
  inputValue: 0,
  type: "warning",
  inputPlaceholder: 'I agree to <a href="#blahblahMore"></a> Your new Rate is :'+newRate,
  showCancelButton: true,
  confirmButtonText: 'Confirm',
  showLoaderOnConfirm: true,
  preConfirm: function(result) {
    return new Promise(function(resolve, reject) {
      if (result) {
        $.post("my.php", {
          Data: data
        })
        .done(
          function(json_data) {
            var data_array = $.parseJSON(json_data);
            var moreDetails = '';
            var resulting = 'error';
            var details = "Transaction Declined"
            if (data_array["trxApproved"] == true) {
              resulting = 'success';
              details = "Confirmed"
              moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
                "<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
            }
            swal({
              type: resulting,
              title: details,
              html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
            });
          }
        );
        resolve();
      } else {
          reject('You must agree to our Terms & Conditions ');
      }
    });
  },
  allowOutsideClick: false
  }).then(function(json_data) {

  })
});

5 个答案:

答案 0 :(得分:32)

更新(2017年1月):此问题已在第7版中修复:v7 upgrade guide ↗

您需要向Promise添加拒绝处理程序。或者,您可以使用.catch(swal.noop)作为简单方法来简单地抑制错误:

swal('...')
  .catch(swal.noop);

PS。您正在使用的软件包称为SweetAlert 2 ,而不是SweetAlert。在将来的问题中,请提及它,以便您可以获得更多相关答案。

答案 1 :(得分:14)

按下取消按钮时,SweetAlert2拒绝结果承诺。你可以handle that

swal({
  …
}).then(function(json_data) {
  …
}, function(dismiss) {
  if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
    // ignore
  } else {
    throw dismiss;
  }
})

如果您不需要对json_data执行任何操作,也可以使用catch method

答案 2 :(得分:4)

new Promise(function(resolve, reject) {没有必要。 $.post()返回一个jQuery promise对象。

可能的解决方案将Promise.reject()替换为new Promise()构造函数;已移除.then()作为第一次swal()来电的选项;模式似乎期望从Promise返回preConfirm,但不确定从.done()以外的json_data返回的值是什么。

swal({
  title: "Confirm",
  input: 'checkbox',
  inputValue: 0,
  type: "warning",
  inputPlaceholder: 'I agree to <a href="#blahblahMore"></a>',
  showCancelButton: true,
  confirmButtonText: 'Confirm',
  showLoaderOnConfirm: true,
  preConfirm: function(result) {
      if (result) {
        return $.post("my.php", {
          Data: data
        })
        .done(
          function(json_data) {
            var data_array = $.parseJSON(json_data);
            var moreDetails = '';
            var resulting = 'error';
            var details = "Transaction Declined"
            if (data_array["trxApproved"] == true) {
              resulting = 'success';
              details = "Confirmed"
              moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
                "<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
            }
            swal({
              type: resulting,
              title: details,
              html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
            });
          }
        );
      } else {
          return Promise.reject('You must agree to our Terms & Conditions ');
      }
  },
  allowOutsideClick: false
});

答案 3 :(得分:0)

您需要赶上取消操作

swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then(function(json_data) {
  //delete item
}, function(dismiss) {
  if (dismiss === 'cancel' || dismiss === 'close') {
    // ignore
  } 
})

答案 4 :(得分:0)

添加catch(swal.noop);最后,swal函数将解决此问题

例如:

swal({

}).then(function() {

}).catch(swal.noop);