-
Notifications
You must be signed in to change notification settings - Fork 29
/
15.async-await-pizza.js
116 lines (85 loc) · 2.47 KB
/
15.async-await-pizza.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
function makeDough() {
console.log("haciendo masa...");
return new Promise((resolve, reject) => {
const dough = {
components: [],
add(c) {
this.components.push(c);
}
};
setTimeout(() => resolve(dough), 1000);
});
}
function makeSauce(tipo) {
console.log(`haciendo salsa tipo ${tipo}...`);
return new Promise((resolve, reject) => {
const cheese = {
determineCheese() {
return;
}
}
setTimeout(() => resolve(cheese), 1000);
});
}
function grateCheese(sauce) {
console.log("haciendo queso...");
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 1000);
});
}
// example from https://medium.com/@bluepnume/even-with-async-await-you-probably-still-need-promises-9b259854c161
// |-------- dough --------> |-------- sauce --------> |-- cheese -->
async function makePizza(sauceType = 'red') {
let dough = await makeDough();
let sauce = await makeSauce(sauceType);
let cheese = await grateCheese(sauce.determineCheese());
dough.add(sauce);
dough.add(cheese);
return dough;
}
// quiero algo así:
// |-------- dough -------->
// |-------- sauce --------> |-- cheese -->
async function makePizza2(sauceType = 'red') {
let [ dough, sauce ] = await Promise.all([ makeDough(), makeSauce(sauceType) ]);
let cheese = await grateCheese(sauce.determineCheese());
dough.add(sauce);
dough.add(cheese);
return dough;
}
// puede darme algo así:
// |-------- dough -------->
// |--- sauce ---> |-- cheese -->
// quiero algo así:
// |-------- dough -------->
// |------ sauce -----> |-- cheese -->
async function makePizza3(sauceType = 'red') {
let doughPromise = makeDough();
let saucePromise = makeSauce(sauceType);
let cheesePromise = saucePromise.then(sauce => {
return grateCheese(sauce.determineCheese());
});
return Promise.all([ doughPromise, saucePromise, cheesePromise ])
.then(([ dough, sauce, cheese ]) => {
dough.add(sauce);
dough.add(cheese);
return dough;
});
}
// lo mismo, puramente async/await
async function makePizza4(sauceType = 'red') {
let doughPromise = makeDough();
let saucePromise = makeSauce(sauceType);
let sauce = await saucePromise;
let cheese = await grateCheese(sauce.determineCheese());
let dough = await doughPromise;
dough.add(sauce);
dough.add(cheese);
return dough;
}
module.exports = {
makePizza,
makePizza2,
makePizza3,
makePizza4
};