Promise.then的第二個參數與catch的區別


1、異常捕獲

getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function funcA(comments) { // 這里的異常,then的第二個參數捕獲不到
  console.log("resolved: ", comments); }, function funcB(err){ console.log("rejected: ", err); });

2、冒泡性質

Promise 對象的錯誤具有“冒泡”性質,會一直向后傳遞,直到被捕獲為止。也就是說,錯誤總是會被下一個catch語句捕獲。

getJSON('/post/1.json').then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // some code
}).catch(function(error) { // 處理前面三個Promise產生的錯誤
});

上面代碼中,一共有三個 Promise 對象:一個由getJSON產生,兩個由then產生。它們之中任何一個拋出的錯誤,都會被最后一個catch捕獲。

這也是then的第二個參數處理不了的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM