Error Handling
const turnonLaptop = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`노트북 실행.`), 1000);
});
const loginBlog = blog =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`Error! ${blog} => 블로그 진입.`)), 1000);
});
const writePost = post =>
new Promise ((resolve, reject) => {
setTimeout(() => resolve(`${post} => 게시 완료.`), 1000);
});
producer 코드를 작성했다.
turnOnlaptop() //
.then(openBlog)
.then(writePost)
.then(console.log);
// VM86:7 Uncaught (in promise) Error: Error! 노트북 실행. => 블로그 진입.
then만 붙이면 이렇게 openBlog에서 reject된 에러를 catch하지 못해 uncaught Error가 난다.
turnonLaptop() //
.then(loginBlog)
.catch(error => {
return `비밀번호 찾기`;
})
.then(writePost)
.then(console.log)
.catch(console.log);
// 비밀번호 찾기 => 게시 완료.
catch를 사용하면 내가 원하는 곳에서 error를 handling할 수 있다.
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko/
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [코딩애플] 스크롤 이벤트 (0) | 2023.01.11 |
|---|---|
| [드림코딩] 콜백함수 (4) : 콜백지옥 탈출, Promise (callback hell 코드개선하기) (0) | 2022.10.04 |
| [드림코딩] 콜백함수 (2) : 콜백지옥 탈출, Promise (State, Producing) (0) | 2022.07.22 |
| [드림코딩] 콜백함수 (1) : 콜백지옥 예시 (0) | 2022.07.22 |
| [mdn, 드림코딩, 코딩애플] 콜백함수 (1) : 동기와 비동기 개념 (0) | 2022.07.12 |