2016-11-10 109 views
0

我有一個功能,點擊我使用sweetalert2。這是函數:Javascript - Uncaught(承諾)

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未捕獲的(以諾)定時器

如何我可以避免這種情況,我做錯了什麼?

回答

0

問題是,你通常不應該調用一個函數來返回一個承諾,而不是用這個承諾做一些事情。在這種情況下,承諾返回函數是swal$.post。如果你忽略了退還的承諾,那麼你不會等待它完成。您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; 
    }) 
} 
+0

我已經使用您的建議編輯了我的代碼,但仍然收到相同的錯誤 – Leff

+0

請參閱我的編輯以在最後添加診斷處理程序。 – JohnLock

+0

可能你只需要忽略對「成功」警戒承諾的拒絕。看我的編輯。 – JohnLock