Skip to content

Commit 8a27656

Browse files
committed
promises
1 parent dece431 commit 8a27656

File tree

1 file changed

+57
-10
lines changed

1 file changed

+57
-10
lines changed

playground/promises.html

Lines changed: 57 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,64 @@
11
<!DOCTYPE html>
22
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
6+
<title>Promises</title>
7+
<link rel="stylesheet" href="../base.css" />
8+
</head>
39

4-
<head>
5-
<meta charset="UTF-8">
6-
<meta name="viewport" content="width=device-width,initial-scale=1.0">
7-
<title>Promises</title>
8-
<link rel="stylesheet" href="../base.css">
9-
</head>
10+
<body>
11+
<script>
12+
function makePizza(toppings = []) {
13+
return (pizzaPromise = new Promise((resolve, reject) => {
14+
const amountOfTimeToBake = 500 + (toppings.length * 300)
15+
// wait 1 second for pizza to cook
16+
setTimeout(() => {
17+
// when you are ready, you can resolve this promise
18+
resolve(
19+
`Here is your pizza 🍕 with the toppings ${toppings.join(" ")}`
20+
);
21+
}, amountOfTimeToBake);
22+
// if something went wrong, we can reject this promise
23+
}));
24+
}
25+
26+
// console.log('first')
27+
// // running promises sequentially
28+
// makePizza(["Pepperoni"]).then((pizza) => {
29+
// console.log(pizza);
30+
// return makePizza(["Bacon", "Onion", "Mushroom"])
31+
// .then((pizza) => {
32+
// console.log(pizza);
33+
// return makePizza(["Anchovie", "Olives", "Chicken"])
34+
// .then((pizza) => {
35+
// console.log(pizza);
36+
// });
37+
// });
38+
// });
39+
// console.log('after')
1040

11-
<body>
12-
<script>
41+
// running promises concurrently
42+
const pizzaPromise1 = makePizza(['Onion', 'Mushroom', 'Green Pepper', 'Tomato', 'Spinach'])
43+
const pizzaPromise2 = makePizza(['Feta'])
44+
const pizzaPromise3 = makePizza(['Pineapple', 'Ham'])
45+
// resolves when ALL promises are filled
46+
const dinnerPromise = Promise.all([pizzaPromise1, pizzaPromise2, pizzaPromise3])
47+
48+
dinnerPromise.then(function(pizzas){
49+
const [ veggie, plain, nasty ] = pizzas
50+
console.log('here are all of the pizzas!')
51+
console.log(veggie)
52+
console.log(plain)
53+
console.log(nasty)
54+
});
1355

14-
</script>
15-
</body>
56+
// returns first promise to be fulfilled
57+
const firstPizza = Promise.race([pizzaPromise1, pizzaPromise2, pizzaPromise3])
58+
firstPizza.then(pizza => {
59+
console.log('race first pizza: ',pizza)
60+
})
1661

62+
</script>
63+
</body>
1764
</html>

0 commit comments

Comments
 (0)