簡體   English   中英

有沒有調試失敗的承諾的好方法?

[英]Is there a good way to debug a failing promise?

我對諾言的.then塊有錯字,諾言不斷失敗。 我想我沒有意識到是否有一種類型可以使用.catch 花了很多時間才弄清楚這是個錯誤(繼續假設,promise / async / etc調用有問題)。

有沒有辦法讓JS告訴我“嘿,您的.then塊有錯誤!”

     searchAPI(name)
      .then(data => {
        // typo was LowerCase instead of toLowerCase
        let filtereddowndata = data
          .filter(item =>
            item.title.toLowerCase().includes(name.LowerCase())
          )
               etc etc

      })
      .catch(function() {
        console.log("no match found"); // kept going here.
      });

發送到.catch()的實際錯誤(您在代碼中忽略了該錯誤)將為您提供一個很好的線索,說明為什么觸發了.catch() 使用這樣的東西:

.catch(function(e) { 
    console.log(e);
    // any other processing code here
 });

我總是確保將實際錯誤記錄在我的.catch()語句中,這樣我就可以始終准確地看到它被觸發的原因,並且不要盲目地假設代碼是如何到達這里的。

這也是為什么node.js的使它成為一個控制台警告(並最終運行時錯誤),當你沒有任何.catch()因為try/catch建成.then()如果你隱藏你的錯誤不要將自己暴露在.catch()


在這種情況下,上面的內容足以給您確切的錯誤。 但是在其他情況下(出於調試目的),有時您可以在代碼的更本地化區域周圍插入自己的try / catch語句而受益。 那也將向您顯示.then()處理程序中發生的事情。

您可以運行此代碼段以查看實際錯誤。

  // simulate your searchAPI() call function searchAPI() { return new Promise(resolve => { resolve([{title: "Superman"}, {title: "Spiderman"}]); }); } let name = "Joe"; searchAPI(name).then(data => { // typo was LowerCase instead of toLowerCase let filtereddowndata = data.filter(item => item.title.toLowerCase().includes(name.LowerCase()) ); }).catch(function(e) { // console.log(e) will work with normal Javascript // here in a stackoverflow snippet where console.log has been replaced // you have to look at console.log(e.message) to see the error console.log("searchAPI failed - ", e.message); }); 

我只能強調@jfriend的答案,您應該始終拒絕使用正確的錯誤消息並將其記錄下來。

但是,了解承諾如何被拒絕以及哪些.catch()回調將從何處處理拒絕也很重要。 通過不使用傳統的.then(…).catch(…)模式 ,甚至可以使用來自它的函數標記每個錯誤,可以更好地區分錯誤源

在您的情況下,錯誤消息“ 找不到匹配項 ”被放錯了位置,因為它暗示searchAPI失敗,但這不是到達catch處理程序的唯一原因。 相反,更好的模式是

function searchAPI(name) {
    …
    return Promise.reject(new Error("No match found"));
    //                              ^^^^^^^^^^^^^^^^ error message (or error code)
}   //                              thrown exactly where the error actually occurred

searchAPI(name).then(data => {
    let filtereddowndata = data.filter(item =>
        item.title.toLowerCase().includes(name.LowerCase())
    )
    …
}, err => { // <- second `then` argument
    console.log("Error from searchAPI", err);
});
// would now cause an unhandled rejection about the LowerCase method call

您當然可以將其與catch處理程序結合使用:

searchAPI(name).then(data => {
    let filtereddowndata = data.filter(item =>
        item.title.toLowerCase().includes(name.LowerCase())
    )
    …
}, err => { // <- second `then` argument
    console.log("Error from searchAPI", err);
}).catch(err => {
    console.error("Error from promise callback", err);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM