티스토리 뷰
- Promise is a JavaScript object for asynchronous operation
- state: pending -> 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. Consumers: then, catch, finally
promise
.then(value => {
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => console.log('finally')
});
3. Promise chaning
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)); // 5
4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('HEN'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`error! ${hen} => EGG`)), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve((`${egg} => COOK`), 1000));
});
getHen()
.then(getEgg)
.then(cook)
.then(console.log)
.catch(console.log);
// error! HEN => EGG
5. Callback 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 ${user.name}, you have a ${user.role} roles`))
.catch(console.log);
※출처
'JavaScript & TypeScript' 카테고리의 다른 글
React - LifeCycle API (0) | 2020.11.24 |
---|---|
React - 시작하기 (0) | 2020.11.23 |
10. Callback (0) | 2020.11.15 |
9. JSON (0) | 2020.11.15 |
8. Array APIs (0) | 2020.11.14 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 김영한 http
- REST API
- ㅇㄷㅇㅈ
- HTTP 완벽 가이드
- BOJ
- 패스트캠퍼스 컴퓨터공학 완주반
- JS 딥다이브
- 김영한 JPA
- js promise
- HTTP 완벽가이드
- 킹수빈닷컴
- Spring Security
- js api
- GCP
- 모던자바스크립트
- js array
- 이펙티브자바 스터디
- JPA 연관관계 매핑
- 드림코딩
- 프로그래머스 SQL
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- http
- dreamcoding
- 백기선 스터디
- 이펙티브자바 아이템60
- 이펙티브자바 아이템59
- 이펙티브자바
- java
- 프로그래머스
- 백준
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
글 보관함