Javascript-未捕获(承诺) [英] Javascript - Uncaught (in promise)
问题描述
我有一个单击功能,可以使用 sweetalert2 .这是功能:
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未捕获(承诺)的计时器
sweetalert2.min.js:1 Uncaught (in promise) timer
如何避免这种情况,我在做什么错了?
How can I avoid that, what am I doing wrong?
推荐答案
问题是,通常情况下,您不应在未对诺言做任何事情的情况下调用返回诺言的函数.在这种情况下,承诺返回函数为swal
和$.post
.如果您忽略返回的承诺,那么您就不必等待其完成.您的then
处理程序可以返回一个诺言,以继续诺言链,如下所示:
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;
})
}
这篇关于Javascript-未捕获(承诺)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!