Promise中的then第二個參數和catch有什么區別?


Promise中的then第二個參數和catch有什么區別?

首頁我們先要區分幾個概念,第一,reject是用來拋出異常的,catch是用來處理異常的;
第二:reject是Promise的方法,而then和catch是Promise實例的方法(Promise.prototype.then 和 Promise.prototype.catch)。

1. 區別

主要區別就是,如果在then的第一個函數里拋出了異常,后面的catch能捕獲到,而then的第二個函數捕獲不到。

catch只是一個語法糖而己 還是通過then 來處理的,大概如下所示

 

Promise.prototype.catch = function(fn){
    return this.then(null,fn);
}
then的第二個參數和catch捕獲錯誤信息的時候會就近原則,如果是promise內部報錯,reject拋出錯誤后,then的第二個參數和catch方法都存在的情況下,只有then的第二個參數能捕獲到,如果then的第二個參數不存在,則catch方法會捕獲到。

const promise = new Promise((resolve, rejected) => {
    throw new Error('test');
});

//此時只有then的第二個參數可以捕獲到錯誤信息
promise.then(res => {
    //
}, err => {
    console.log(err);
}).catch(err1 => {
    console.log(err1);
});


//此時catch方法可以捕獲到錯誤信息
promise.then(res => {
    //
}).catch(err1 => {
    console.log(err1);
});


//此時只有then的第二個參數可以捕獲到Promise內部拋出的錯誤信息
promise.then(res => {
    throw new Error('hello');
}, err => {
    console.log(err);
}).catch(err1 => {
    console.log(err1);
});

//此時只有then的第二個參數可以捕獲到Promise內部拋出的錯誤信息
promise.then(res => {
    throw new Error('hello');
}, err => {
    console.log(err);
});


//此時catch可以捕獲到Promise內部拋出的錯誤信息
promise.then(res => {
    throw new Error('hello');
}).catch(err1 => {
    console.log(err1);
});

2. 兩個捕獲方法的比較

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });
上面代碼中,第二種寫法要好於第一種寫法,理由是第二種寫法可以捕獲前面then方法執行中的錯誤,也更接近同步的寫法(try/catch)。因此,建議總是使用catch方法,而不使用then方法的第二個參數。






免責聲明!

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



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