|
1 | 1 | <!DOCTYPE html>
|
2 | 2 | <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> |
3 | 9 |
|
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') |
10 | 40 |
|
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 | + }); |
13 | 55 |
|
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 | + }) |
16 | 61 |
|
| 62 | + </script> |
| 63 | + </body> |
17 | 64 | </html>
|
0 commit comments