Leff Leff - 23 days ago 17
Javascript Question

Javascript - Uncaught (in promise)

I have a function on click for which I use sweetalert2. This is the function:

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;
}
})
}


Everything works fine but I get an error for the timer:


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


How can I avoid that, what am I doing wrong?

Answer

The problem is that you should generally never call a function that returns a promise without doing something with that promise. In this case the promise-returning functions are swal and $.post. If you ignore the returned promise then you're not waiting for it to complete. Your then handlers can return a promise to continue the promise chain, like this:

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;
    })
}
Comments