Last active
November 27, 2020 22:37
-
-
Save woudsma/fe8598b1f41453208f0661f90ecdb98b to your computer and use it in GitHub Desktop.
Recursive try/catch statements for async/await functions in a nested object (using .catch)
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
// Simulates try/catch statements wrapping async functions in (nested) object | |
// Returns copy of original object with basic promise-rejection handling for async functions using .catch | |
// Saves the time of writing try/catch statements in every single async function | |
const trycatch = obj => Object.keys(obj) | |
.reduce((acc, curr) => ({ ...acc, [curr]: obj[curr] instanceof Function | |
? (...args) => obj[curr](...args).catch(::console.error) | |
: trycatch(obj[curr]) }), {}) | |
// Example | |
const actions = (db) => trycatch({ | |
async test(id) { | |
console.log(id) | |
}, | |
get: { | |
async user(id) { | |
await db.users.get(id) | |
}, | |
async session(id) { | |
throw new Error('TODO') | |
}, | |
... | |
} | |
}) | |
// Instead of: | |
const actions = (db) => ({ | |
async test(id) { | |
try { | |
console.log(id) | |
} catch(err) { | |
console.error(err) | |
} | |
}, | |
get: { | |
async user(id) { | |
try { | |
await db.users.get(id) | |
} catch(err) { | |
console.error(err) | |
} | |
}, | |
async session(id) { | |
try { | |
throw new Error('TODO') | |
} catch(err) { | |
console.error(err) | |
} | |
}, | |
... | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment