Skip to content

Instantly share code, notes, and snippets.

@tbxark
Created January 24, 2025 01:07
Show Gist options
  • Select an option

  • Save tbxark/a199445e1e4c2044382d77efa4df895c to your computer and use it in GitHub Desktop.

Select an option

Save tbxark/a199445e1e4c2044382d77efa4df895c to your computer and use it in GitHub Desktop.
Safe Assignment
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));
@tbxark
Copy link
Author

tbxark commented Jan 24, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment