Repository navigation
Expand file tree
/
Copy path12_async.js
More file actions
68 lines (55 loc) · 1.51 KB
/
Copy path12_async.js
File metadata and controls
68 lines (55 loc) · 1.51 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
67
68
// async & await
// clear style of using promise :)
// ! 1. async
// async 써보기
// 'async'를 함수 앞에 사용하면,
// 함수 안에 있는 코드 블럭들이 Promise로 변환
async function fetchUser() {
// do network request in 10 secs..
return 'ellie';
}
const user = fetchUser();
user.then(console.log);
console.log(user);
// ! 2. await
// 기다려
// 'async'가 붙은 함수 안에서만 사용 가능
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function getApple() {
await delay(1000);
return '사과';
}
async function getBanana() {
await delay(1000);
return '바나나';
}
async function pickFruits() {
// callback Hell
// return getApple().then((apple) => {
// return getBanana().then((banana) => `${apple} + ${banana}`);
// });
// 병렬적으로 기능을 수행할 수 있는 경우 아래처럼 코드 작성 x
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple} + ${banana}`;
}
pickFruits().then((value) => console.log(value));
// ! 3. useful Promise APIs
function pickAllFruits() {
return Promise.all([getApple(), getBanana()]).then((fruits) =>
fruits.join(', ')
);
}
pickFruits().then((value) =>
console.log(`useful Promise APIs 'all': ${value}`)
);
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}
pickOnlyOne().then((value) =>
console.log(`useful Promise APIs 'race': ${value}`)
);