前言
在最近的項目中,用到了es6的promise語法,發現promise.prototype.catch 並不只是單單reject拋出的回調函數,所以今天做一些筆錄,防止以后在項目中又碰到這樣的問題。
先介紹一下promise.prototype.catch
Promise.prototype.catch 方法是 .then(null, rejection) 或是 .then(undefined, rejection)的別名,用於指定發生錯誤時的回調函數。
如果Promise 對象狀態變為resolved
,則會調用then
方法指定的回調函數;如果異步操作拋出錯誤,狀態就會變為rejected
,就會調用catch
方法指定的回調函數,處理這個錯誤。另外,then
方法指定的回調函數,如果運行中拋出錯誤,也會被catch
方法捕獲。
下面是摘抄阮一峰的es6入門的
p.then((val) => console.log('fulfilled:', val)) .catch((err) => console.log('rejected', err)); // 等同於 p.then((val) => console.log('fulfilled:', val)) .then(null, (err) => console.log("rejected:", err));
下面是我自己寫的例子
const testPromise = new Promise(function (resolve, reject) { let a = 5 if (a === 5) { resolve('success') } else { reject('catch error') } }) testPromise.then(res => { throw new Error('then error') }).catch(err => { console.log('catch error') console.log(err) })
這個例子最終會先輸出catch error,然后再拋出錯誤信息。
總結
then中拋出錯誤,就會調用promise.prototype.catch的回調函數。