-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise.js
More file actions
66 lines (59 loc) · 1.79 KB
/
promise.js
File metadata and controls
66 lines (59 loc) · 1.79 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'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 executer runs automatically
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
// resolve('sill');
reject(new Error('no network'));
}, 2000);
});
// 2. Consumer: 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));
// 4. Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`닭`), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`error! ${hen} => 달걀`)), 1000); // resolve(`${hen} => 달걀`), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 달걀 프라이`), 1000);
});
getHen()
.then(getEgg) // hen => getEgg(hen)
.catch(error => { // 달걀을 받아오는 함수의 에러를 처리하고 싶을 때는 그 다음 라인에 catch를 작성!
return '빵';
})
.then(cook) // (egg => cook(egg)
.then(console.log) // meal => console.log(meal)
.catch(console.log);