VIDEO
동영상 수강 전 본문 내용 스캔.
동영상 수강 후 본문 내용 스캔.
안 보고 직접 코드 타이핑 하기.
promise.js
'use strict';
// Promise is a JavaScrit object for asynchronous operation.
// State: pendding → fulfilled or rejected
// Producer vs. Consumer
// 1. Producer
// When new Promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
});
// 2. Consumer: then, catch, finally
// 주의: then, catch, finally는 한 구문이라, 끝에만 ; (세미콜론) 붙임.
promise
.then((value) => {
// 성공 시 실행
console.log(value);
})
.catch((error) => {
// 실패 시 실행
console.log(error);
})
.finally(() => {
// 성공・실패 시 실행
console.log('finally');
});
// 3. Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
fetchNumber
.then((num) => num * 2) // 1 => 1*2 = 2
.then((num) => num * 3) // 2 => 2*3 = 6
.then((num) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000); // 6 - 1 = 5
});
})
.then((num) => console.log(num)); // 5 => 5
// then은 value를 전달할 수도 있고, Promise 자체를 전달할 수도 있음.
// 총 2초 소요.
// 결과값: 5
// 비동기 코드들을 묶어서 (= chaining) 표현 가능.
// Promise를 chaining했을 때 Error 다루는 법 소개.
// 4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('닭'), 1000);
});
const getEgg = (hen) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${hen} => 달걀`), 1000); // 성공 시
// setTimeout(() => reject(new Error(`error! ${hen} => 달걀`)), 1000); // 실패 시
});
const cook = (egg) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 후라이`), 1000);
});
// ******************************************
// const getEgg 부분에서 성공 코드 사용 가정 시
// ******************************************
/*
getHen() // 닭
.then((hen) => getEgg(hen)) // 닭 => 달걀
.then((egg) => cook(egg)) // 닭 => 달걀 => 후라이
.then((meal) => console.log(meal)); // 출력: 닭 => 달걀 => 후라이
// 받아온 value 하나를 그대로 다른 함수의 독립변수로 사용 시 아래처럼 표현 가능.
getHen() // 닭
.then(getEgg) // 닭 => 달걀
.then(cook) // 닭 => 달걀 => 후라이
.then(console.log); // 출력: 닭 => 달걀 => 후라이
// 위 축약된 코드를 아래처럼 한 줄로 표현 가능.
getHen().then(getEgg).then(cook).then(console.log); // 출력: 닭 => 달걀 => 후라이
*/
// 위처럼 한 줄로 하면 가독성 떨어지므로, 아래처럼 // 붙이고 Enter키 누르면 자동 줄바꿈 됨.
getHen() //
.then(getEgg)
.then(cook)
.then(console.log); // 성공 시 출력: 닭 => 달걀 => 후라이
// ******************************************
// const getEgg 부분에서 실패 코드 사용 가정 시
// ******************************************
// 에러 대비 코드 사용 X
getHen() //
.then(getEgg)
.then(cook)
.then(console.log)
.catch(console.log); // 출력: Error: error! 닭 => 달걀
// 에러 대비 코드 사용 O
getHen() //
.then(getEgg)
.catch((error) => {
// 실패 시 대체 코드
return '빵';
})
.then(cook)
.then(console.log)
.catch(console.log); // 출력: 빵 => 후라이
callback-to-promise.js
'use strict';
// Callback Hell example
/*
class UserStorage {
loginUser(id, passwod, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'ellie') {
onSuccess({ name: 'ellie', role: 'admin' });
} else {
onError(new Error('no access'));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(
id,
password,
(user) => {
userStorage.getRoles(
user,
(userWithRole) => {
// userWidthRole는 { name: 'ellie', role: 'admin' } 객체 가리키는 임의의 매개변수임.
alert(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
);
// 결과값 : Hello ellie, you have a admin role
// alert(`Hello ${user.name}, you have a ${user.role} role`);
// 결과값 : Hello undefined, you have a undefined role
},
(error) => {
console.log(error);
}
);
},
(error) => {
console.log(error);
}
);
*/
// Callback Hell Escape by using Promise
class UserStorage {
loginUser(id, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
resolve(id);
} else {
reject(new Error('not found'));
}
}, 2000);
});
}
getRoles(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user === 'ellie') {
resolve({ name: 'ellie', role: 'admin' });
} else {
reject(new Error('no access'));
}
}, 1000);
});
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage
.loginUser(id, password)
.then(userStorage.getRoles) // 의미: .then(user => userStorage.getRoles(user))
.then((user) => alert(`Hello ${user .name}, you have a ${user .role} role.`))
.catch(console.log);
주소 복사
랜덤 이동
최신댓글