Created
April 1, 2024 20:24
-
-
Save ryanmorr/108d45f6c0f5d6214bcccfee8201b022 to your computer and use it in GitHub Desktop.
Wrap a try/catch block with a promise for easy error handling
This file contains 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 attempt(fn) { | |
return new Promise((resolve, reject) => { | |
try { | |
resolve(fn()); | |
} catch(e) { | |
reject(e); | |
} | |
}); | |
} | |
// Usage: | |
attempt(() => (0)()).then((val) => { | |
console.log('pass'); | |
}).catch((e) => { | |
console.log('fail'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment