promise체이닝에서 에러가 발생되면 제어흐름상 제일 가까운 rejection핸들러에서 처리할 수 있다.
fetch('user.json')
.then(response => response.json()) // promise체이닝시작
.then(user =>{
return fetch(`https://api.github.com/users/iliakan`)})
.then(response =>{
if(!response.ok){
throw new Error("dsfdf");
}
return response.json();})
.then(githubUser => new Promise((resolve, reject) => {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
}))
.catch(error => console.log(error.message));
// 실행 순서: catch -> then
new Promise((resolve, reject) => {
throw new Error("에러 발생!");
}).catch(function(error) {
console.log("에러가 잘 처리되었습니다. 정상적으로 실행이 이어집니다.");
}).then(() => console.log("다음 핸들러가 실행됩니다."));
new Promise(function() {
noSuchFunction(); // 존재하지 않는 함수를 호출하기 때문에 에러가 발생함
})
.then(() => {
// 성공상태의 프라미스를 처리하는 핸들러. 한 개 혹은 여러 개가 있을 수 있음
}); // 끝에 .catch가 없음!
window.addEventListener('unhandledrejection', function(event) {
console.log(event.promise); // [object Promise] - 에러를 생성하는 프라미스
console.log(event.reason); // Error: 에러 발생! - 처리하지 못한 에러 객체
});