원하는 순서대로 결과를 이끌어내기 위해 고안된 콜백함수! 그러나 복잡한 기능을 구현하기 시작하면 콜백함수가 꼬리를 무는 콜백지옥이 발생한다. 이를 해결하기 위한 promise는 어떤 기능인지 알아보도록 하자!
Promise : javascript가 제공하는 콜백함수 대신 간편하게 쓸 수 있는 오브젝트. 성공, 실패에 따른 결과를 알려준다.
//Promise is a JavaScript object for asynchronous operation.
//1. State: 진행되었는지 또는 끝났는지? pending => fulfilled or rejected
//2. Producer vs Consumer
//1.Producer
//when new promise is created, the executer 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. Consumers: then, catch, finally
//then: constructor가 완료된 '다음'진행 할 수 있게 해주는 메소드, promise 값이나 또 다른 promise를 받는다.
//catch: 에러가 났을 때 다음 진행을 위한 메소드
//finally: 성공, 실패 여부에 상관없이 마지막에 출력됨.
promise
.then((value) => {
console.log(value);
})
.catch((value) => {
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)
.then(num => num * 3)
.then(num => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000);
});
})
.then(num => console.log(num));
//4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('🐓'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${hen} => 🥚`), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 🍳`), 1000);
});
getHen()
.then(hen => getEgg(hen)) //value를 그대로 전해주는 것이라면 .then(getEgg) 로 표현 가능!
.then(egg => cook(egg))
.then(meal => console.log(meal))
.catch(console.log(meal));
//catch의 순서를 바꾸면서 에러 시 결과를 바꿀 수 있다.
//Callback Hell => 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 => alert(`Hello ${userWithRole.name}, you have a ${userWirhRole} role`))
.catch(console.log)
//확실히 더 깔끔해졌다!