Created
January 24, 2025 01:07
-
-
Save tbxark/a199445e1e4c2044382d77efa4df895c to your computer and use it in GitHub Desktop.
Safe Assignment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function tryCatch(fn, ...args) { | |
| try { | |
| const result = fn.apply(null, args); | |
| if (result.then) { | |
| return new Promise(resolve => { | |
| result | |
| .then(v => resolve([undefined, v])) | |
| .catch(e => resolve([e, undefined])) | |
| }); | |
| } | |
| return [undefined, result]; | |
| } catch (e) { | |
| return [e, undefined]; | |
| } | |
| } | |
| function throws() { | |
| throw new Error("It threw"); | |
| } | |
| async function asyncSum(first, second) { | |
| return first + second; | |
| } | |
| async function asyncThrows() { | |
| throw new Error("It throws async"); | |
| } | |
| // returns a sum | |
| // prints [ undefined, 2 ] | |
| console.log(tryCatch(Math.sqrt, 4)); | |
| // returns an error | |
| // prints [ Error: 'It threw', undefined ] | |
| console.log(tryCatch(throws)); | |
| // returns a promise resolving to value | |
| // prints [ undefined, 3 ] | |
| console.log(await tryCatch(asyncSum, 1, 2)); | |
| // returns a promise resolving to error | |
| // prints [ Error: 'It throws async', undefined ] | |
| console.log(await tryCatch(asyncThrows)); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://nalanj.dev/posts/safe-assignment/