Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 운영체제
- 딕셔너리
- BFS
- 가상메모리 관리
- 스택
- level2
- level3
- dfs
- 수학
- dict
- 브루트포스
- 그리디
- 힙
- 코딩테스트
- 다이나믹 프로그래밍
- 재귀
- 파이썬
- N과M
- DP
- 구현
- BOJ
- level0
- 가상메모리
- 백준
- MYSQL
- level1
- 프로그래머스
- 다익스트라
- python
- programmers
Archives
- Today
- Total
동캄의 코딩도장
JS [promise] 본문
'use strict';
// 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. Consummers: then, catch, finally
promise.
then((value)=>{
console.log(value);
})
.catch(error=>{
console.log(error);
})
.finally(()=>console.log('finally'));
// 3. Promise channing
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 Handing
const getHen = ()=>
new Promise((resolve,reject)=>{
setTimeout(() => {
resolve('chicken');
}, 1000);
});
const getEgg = hen=>
new Promise((resolve,reject)=>{
setTimeout(() => {
resolve(`${hen} => egg`)
}, 1000);
});
const cook = egg =>
new Promise((resolve,reject) =>{
setTimeout(() => {
resolve(`${egg} => fried egg`)
}, 1000);
})
// getHen()
// .then(hen=>getEgg(hen))
// .then(egg=>cook(egg))
// .then(meal=>console.log(meal));
getHen()
.then(getEgg)
.catch(error=>{
return 'bread';
})
.then(cook)
.then(console.log);
'front > HTML&CSS&JS' 카테고리의 다른 글
JS [async] (0) | 2022.01.25 |
---|---|
JS [callback-to-promise 예제] (0) | 2022.01.25 |
JS [call back] (0) | 2022.01.25 |
JS [JSON] (0) | 2022.01.25 |
JS [array API] (0) | 2022.01.24 |