Promise.prototype.catch(): 是.then(null, rejection)的別名,用于指定發生錯誤時的回調函數
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));// catch方法可以捕獲then方法中拋出的錯誤
var promise = new Promise(function (resolve, reject) {throw nuw Error('test');
});
promise.catch(function (error) {console.log(error);
});
// 如果Promise狀態已經變成Resolved, 再拋出錯誤是無效的.
var promise = new Promise(function (resolve, reject) {resolve('ok');throw new Error('test from promise');
});
promise.then(function (value) { console.log(value) }).catch(function (error) { console.log(error) });
// 如果沒有使用catch方法指定錯誤處理的回調函數,Promise對象拋出的錯誤不會傳遞到外層代碼
var someAsyncThing = function() {return new Promise (function (resolve, reject) {resolve(x + 2);});
};someAsyncThing().then(function() {console.log('everything is great');
});// 注:resolve(x + 2) 會報錯,x未定義, 控制臺也確實報錯了,但并不會終止這個腳本,即這個腳本再服務器內執行的退出碼為0
參考《ES6標準入門》(第3版) P280~P282