약속에 관하여.catch 방법의 이해
3584 단어 promise
Promise
의then
방법에 관한 글을 썼는데, 지금은 Promise
원형상catch
에 관한 방법을 설명하고 있다catch
방법은 거절한 상황을 처리하거나 이상한 상황을 던지기 위한 것이다문법
p.catch(onRejected);
p.catch(function(reason){
//
});
매개 변수
onRejected
: Promise
이 거부되었을 때 호출된 하나Function
, 이 함수는 매개 변수reson
: 거부 사유새로운 기능
Promise
예제 코드
반환된 Promise 비헤이비어 상태
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`,e); // "e oh, no!"
//
//Promise.resolve();
}).then(function(value){
console.log('after a catch the chain is restored',value);
}, function (err) {
console.log('Not fired due to the catch',err);
});
:
Success
e oh, no!
after a catch the chain is restored undefined
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`,e); // "e oh, no!"
//
return Promise.resolve();
}).then(function(value){
console.log('after a catch the chain is restored',value);
}, function (err) {
console.log('Not fired due to the catch',err);
});
:
Success
e oh, no!
after a catch the chain is restored undefined
위의 코드를 다음과 같이 변경합니다.
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`,e); // "e oh, no!"
//
return Promise.reject("ssssss");
}).then(function(value){
console.log('after a catch the chain is restored',value);
}, function (err) {
console.log('Not fired due to the catch',err);
});
:
Success
e oh, no!
Not fired due to the catch ssssss
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`,e); // "e oh, no!"
throw "ssssss"
}).then(function(value){
console.log('after a catch the chain is restored',value);
}, function (err) {
console.log('Not fired due to the catch',err);
});
:
Success
e oh, no!
Not fired due to the catch ssssss
위의 코드에서 볼 수 있듯이
catch
되돌아오는 Promise
상태와 then
방법의 행위는 일치합니다. 구체적으로then을 참고하십시오.오류를 던지거나 실패한
Promise
, Promise
catch()를 통해 실패한 onRejected 상태의 결과를 되돌려줍니다.그렇지 않으면 성공적onFulfilld
상태의 데이터가 반환됩니다.예외 포착 행위
// , catch
var p1 = new Promise(function(resolve, reject) {
throw 'Uh-oh!';
});
p1.catch(function(e) {
console.log(e); // "Uh-oh!"
});
// catch
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
throw 'Uncaught Exception!';
}, 1000);
});
p2.catch(function(e) {
console.log(e); //
});
// resolve()
var p3 = new Promise(function(resolve, reject) {
resolve();
throw 'Silenced Exception!';
});
p3.catch(function(e) {
console.log(e); //
});
스캔 관심, 더 많은 글 보기, 프로그래밍 능력 향상