catch() 메서드는 Promise 반환하여 거부된 경우만 다룹니다. Promise.prototype.then(undefined, onRejected)를 호출하는 것과 동일하게 행동합니다.
구문
p.catch(onRejected);
p.catch(function(reason) {
// 거부
});
매개변수
- onRejected
Promise가 거부된 경우 호출되는Function. 이 함수는 인수가 하나 있습니다, 거부 이유(reason).
설명
catch 메서드는 프로미스 합성(composition) 내 오류 처리에 유용할 수 있습니다.
예
catch 메서드 사용
var p1 = new Promise(function(resolve, reject) {
resolve('Success');
});
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
// 다음은 위와 동일하게 행동
p1.then(function(value) {
console.log(value); // "Success!"
return Promise.reject('oh, no!');
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
프로미스는 비동기 콜백 내 발생한 오류를 잡을 수 없습니다
var p1 = new Promise(function(resolve, reject) {
throw 'Uh-oh!';
});
p1.catch(function(e) {
console.log(e); // "Uh-oh!"
});
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
throw 'Uncaught Exception!';
}, 1000);
});
p2.catch(function(e) {
console.log(e); // 이는 전혀 호출되지 않음
});
스펙
브라우저 호환성
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 32 | 29.0 (29.0) | No support | 19 | 7.1 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|
| Basic support | No support | 29.0 (29.0) | No support | No support | 8 | 32 |