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

Fra*_*int 16 javascript ajax jquery 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) {

  })
});
Run Code Online (Sandbox Code Playgroud)

Lim*_*nte 36

更新(2017年1月):此问题已在v7:v7升级指南 fixed中修复


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

swal('...')
  .catch(swal.noop);
Run Code Online (Sandbox Code Playgroud)

PS.你正在使用的包叫做SweetAlert 2,而不是SweetAlert.在将来的问题中,请提及它,以便您可以获得更多相关答案.

  • 谢谢你,把我的最终(占位符)`.then`改为`.done`做了伎俩 (3认同)
  • @Bergi` .done()`[被替换](https://github.com/limonte/sweetalert2/issues/324)由`.catch(swal.noop)`,谢谢你的意见. (3认同)

Ber*_*rgi 14

按下取消按钮时,SweetAlert2拒绝结果承诺.你可以处理:

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;
  }
})
Run Code Online (Sandbox Code Playgroud)

如果您不需要对其执行任何操作json_data,您也可以使用该catch方法.

  • 这是SweetAlert2 :)原来的SweetAlert已经11个月没有了. (2认同)

Inf*_*nfy 5

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

例如:

swal({

}).then(function() {

}).catch(swal.noop);
Run Code Online (Sandbox Code Playgroud)