|
| 1 | +// ****************************** |
| 2 | +// The Async Keyword ****************************** |
| 3 | +// Example 1 |
| 4 | + |
| 5 | +console.log('The Async Keyword') |
| 6 | + |
| 7 | +// const data = axios.get('https://swapi.dev/api/planets/') |
| 8 | + |
| 9 | +// Run the functions in the Browser console |
| 10 | +// function greet() { |
| 11 | +// return 'HELLO!!!' |
| 12 | +// } |
| 13 | +// greet() |
| 14 | + |
| 15 | +// Whatever the value that i'm returning is, the promise that will |
| 16 | +// be returned from greetAsync() will be resolved with that value |
| 17 | +// async function greetAsync() { |
| 18 | +// return 'HELLO async!!!' |
| 19 | +// } |
| 20 | + |
| 21 | +// greetAsync().then((val) => { |
| 22 | +// console.log('PROMISE RESOLVED WITH: ', val); |
| 23 | +// }) |
| 24 | + |
| 25 | +// Example 2 |
| 26 | +// Run the functions in the Browser console |
| 27 | +// async function add(x, y) { |
| 28 | +// return x + y |
| 29 | +// } |
| 30 | +// add() |
| 31 | + |
| 32 | +/* |
| 33 | +How do we return a promise that is not resolved? |
| 34 | +
|
| 35 | +- If we want to return a rejected promise, all that we do is |
| 36 | +raise an exeption. So if we throw an exception, we throw an error, |
| 37 | +that promise will be rejected |
| 38 | +*/ |
| 39 | +async function add(x, y) { |
| 40 | + if(typeof x !== 'number' || typeof y !== 'number') { |
| 41 | + throw ' X and Y must be numbers!' |
| 42 | + } |
| 43 | + return x + y |
| 44 | +} |
| 45 | +add(3, 2) |
| 46 | +add(3, 'a') |
| 47 | +add('e', 'r').then((val) => { |
| 48 | + console.log('PROMISE RESOLVED WITH: ', val); |
| 49 | +}).catch((err) => { |
| 50 | + console.log('PROMISE REJECTED WITH: ', err) |
| 51 | +}) |
| 52 | + |
| 53 | +console.log('\n'); |
| 54 | +add(2, 3) |
| 55 | + .then((val) => { |
| 56 | + console.log('PROMISE RESOLVED WITH: ', val) |
| 57 | + }) |
| 58 | + .catch((err) => { |
| 59 | + console.log('PROMISE REJECTED WITH: ', err) |
| 60 | + }) |
| 61 | + |
| 62 | +// Example 3 |
| 63 | +// Manual Promise creation |
| 64 | +// function add(x, y) { |
| 65 | +// return new Promise((resolve, rejected) => { |
| 66 | +// if (typeof x !== 'number' || typeof y !== 'number') { |
| 67 | +// rejected(' X and Y must be numbers!') |
| 68 | +// } |
| 69 | +// resolve(x + y) |
| 70 | +// }) |
| 71 | +// } |
| 72 | + |
| 73 | +// add(6, 7).then((val) => { |
| 74 | +// console.log('PROMISE RESOLVED WITH: ', val) |
| 75 | +// }).catch((err) => { |
| 76 | +// console.log('PROMISE REJECTED WITH: ', err) |
| 77 | +// }) |
| 78 | +// add('r', 7) |
| 79 | +// .then((val) => { |
| 80 | +// console.log('PROMISE RESOLVED WITH: ', val) |
| 81 | +// }) |
| 82 | +// .catch((err) => { |
| 83 | +// console.log('PROMISE REJECTED WITH: ', err) |
| 84 | +// }) |
0 commit comments