|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Need node.js 23 |
| 4 | + |
| 5 | +const sumSync = (a, b) => { |
| 6 | + if (typeof a !== 'number') throw Error('Expected a: number'); |
| 7 | + if (typeof b !== 'number') throw Error('Expected b: number'); |
| 8 | + return a + b; |
| 9 | +}; |
| 10 | + |
| 11 | +const sumAsync = async (a, b) => { |
| 12 | + if (typeof a !== 'number') throw Error('Expected a: number'); |
| 13 | + if (typeof b !== 'number') throw Error('Expected b: number'); |
| 14 | + return a + b; |
| 15 | +}; |
| 16 | + |
| 17 | +// Call sync, expected 5 |
| 18 | + |
| 19 | +Promise.try(sumSync, 2, 3) |
| 20 | + .then((result) => { |
| 21 | + console.log({ result }); |
| 22 | + }) |
| 23 | + .catch((error) => { |
| 24 | + console.error({ error: error.message }); |
| 25 | + }) |
| 26 | + .finally(() => { |
| 27 | + console.log({ finally: '2+3=5' }); |
| 28 | + }); |
| 29 | + |
| 30 | +// Call sync, expected error |
| 31 | + |
| 32 | +Promise.try(sumSync, '4', 5) |
| 33 | + .then((result) => { |
| 34 | + console.log({ result }); |
| 35 | + }) |
| 36 | + .catch((error) => { |
| 37 | + console.error({ error: error.message }); |
| 38 | + }) |
| 39 | + .finally(() => { |
| 40 | + console.log({ finally: 'Wrong type: a' }); |
| 41 | + }); |
| 42 | + |
| 43 | +// Call async, expected 13 |
| 44 | + |
| 45 | +Promise.try(sumAsync, 6, 7) |
| 46 | + .then((result) => { |
| 47 | + console.log({ result }); |
| 48 | + }) |
| 49 | + .catch((error) => { |
| 50 | + console.error({ error: error.message }); |
| 51 | + }) |
| 52 | + .finally(() => { |
| 53 | + console.log({ finally: '6+7=13' }); |
| 54 | + }); |
| 55 | + |
| 56 | +// Call async, expected error |
| 57 | + |
| 58 | +Promise.try(sumAsync, 8, '9') |
| 59 | + .then((result) => { |
| 60 | + console.log({ result }); |
| 61 | + }) |
| 62 | + .catch((error) => { |
| 63 | + console.error({ error: error.message }); |
| 64 | + }) |
| 65 | + .finally(() => { |
| 66 | + console.log({ finally: 'Wrong type: b' }); |
| 67 | + }); |
0 commit comments