Javascript - Uncaught (in promise)

Javascript - Uncaught (in promise)

本文关键字:promise in Uncaught Javascript      更新时间:2023-09-26

我有一个函数点击,我使用sweetalert2。下面是函数:

publish = function (article) {
   swal({
      title: "Skal du publisere?",
      text: null,
      type: "info",
      showCancelButton: true,
      cancelButtonText: "Avbyrt",
      cancelButtonColor: '#FFF',
      confirmButtonColor: "#2E112D",
      confirmButtonText: "Ja, publisere"
    }).then(function(){
        var articleId = $(article).val();
        $.post("/admin/articles/publish/article", {
            '_token' : $('meta[name="csrf-token"]').attr('content'),
            'articleId': articleId
        }).done(function(){
            $(article).hide();
            return swal({
              type: 'success',
              title: 'Du har publisert den artikkel.',
              showConfirmButton: false,
              timer: 1000
          });
      }).fail(function() {
          return swal({
            type: 'warning',
            title: 'Noeting gikk feil, prov igjen',
            showConfirmButton: false,
            timer: 1000
          });
        });
    }, function(dismiss) {
    // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
      if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
      // ignore
      } else {
        throw dismiss;
      }
    })
}

一切正常,但我得到一个错误的定时器:

sweetalert2.min.js:1 Uncaught (in promise) timer

我怎么能避免,我做错了什么?

问题是,你通常不应该调用一个返回承诺的函数,而不对该承诺做一些事情。在这种情况下,承诺返回函数是swal$.post。如果你忽略返回的promise,那么你就不会等待它完成。你的then处理程序可以返回一个承诺来继续承诺链,像这样:

publish = function (article) {
    return swal({
      title: "Skal du publisere?",
      text: null,
      type: "info",
      showCancelButton: true,
      cancelButtonText: "Avbyrt",
      cancelButtonColor: '#FFF',
      confirmButtonColor: "#2E112D",
      confirmButtonText: "Ja, publisere"
    }).then(function(){
        $(article).hide();
        var articleId = $(article).val();
        return $.post("/admin/articles/publish/article", {
            '_token' : $('meta[name="csrf-token"]').attr('content'),
            'articleId': articleId
        }).then(function(){
            return swal({
              type: 'success',
              title: 'Du har publisert den artikkel.',
              showConfirmButton: false,
              timer: 1000
          }).catch(function(timeout) { });
      });
    }, function(dismiss) {
    // dismiss can be 'overlay', 'cancel', 'close', 'esc', 'timer'
      if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
      // ignore
      } else {
        throw dismiss;
      }
    })
    .catch(function(err) {
        console.error(err);
        throw err;
    })
}

你需要在Promise中添加一个拒绝处理程序。或者,您可以使用.catch(swal.noop)作为一种快速的方法来简单地抑制错误:

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

这个问题在包文档中提到:https://github.com/limonte/sweetalert2#handling-dismissals

还有一个关于这个主题的封闭问题:limonte/sweetalert2#221