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?
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. Yourthen
handlers can return a promise to continue the promise chain, like this:You need to add a rejection handler to the Promise. Alternatively, you can use
.catch(swal.noop)
as a quick way to simply suppress the errors:This issue is mentioned in the package documentation: https://github.com/limonte/sweetalert2#handling-dismissals
Also, there's the closed issue about the subject: limonte/sweetalert2#221