-
Notifications
You must be signed in to change notification settings - Fork 0
/
index3.js
94 lines (78 loc) · 2.15 KB
/
index3.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// async function f1() {
// return 1;
// }
// async function f2() {
// return Promise.resolve(1);
// }
// console.log('1 >> ', f1());
// // f1 함수는 async 키워드가 붙어 있으므로 프로미스를 반환! => Promise { 1 }
// f1().then(function (result) {
// console.log('2 >> ', result);
// });
// console.log('3 >> ', f2());
// f2().then(function (result) {
// console.log('4 >> ', result);
// });
//////////////////////////////////////////////////
// async - await
// async: 함수 앞에 붙이는 키워드
// - 함수만 보고도 비동기 함수임을 유추하고자 함
// - 프로미스를 반환
// await: 기다리다
// - 성공/실패로 프로미스 객체의 실행이 완료되기를 기다림
// - await 뒤에는 프로미스가 오게 됨
// - **async 키워드를 사용한 함수 안에서만 await 키워드를 사용 가능
// async/ await 세트
// 1초 뒤에 과일 배열을 출력하는 코드
function fetchFruits() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
const fruits = ['사과', '레몬', '수박'];
resolve(fruits);
// reject(new Error('알 수 없는 에러 발생!! 아이템을 가져올 수 없음!!'));
}, 1000);
});
}
// 1) promise then() 메서드 사용
// fetchFruits()
// .then(function (f) {
// console.log(f);
// })
// .catch(function (error) {
// console.log(error);
// });
// async-await 키워드 사용시
// 에러처리는 try-catch 구문으로 하게 됨!
async function printItems() {
try {
const fruits = await fetchFruits();
console.log(fruits);
} catch (error) {
console.log(error);
}
}
printItems();
function goMart() {
console.log('마트에 가서 어떤 음료를 살지 고민한다..');
}
function pickDrink() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('고민 끝!!');
product = '제로 콜라';
price = 2000;
resolve();
}, 3000);
});
}
function pay() {
console.log(`상품명: ${product}, 가격: ${price}`);
}
async function exec() {
goMart();
await pickDrink();
pay();
}
let product;
let price;
exec();