Created
April 25, 2021 15:00
-
-
Save Gopikrishna19/7946bcf8aa5b9507820294f5f208eceb to your computer and use it in GitHub Desktop.
try catch
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
const something = () => new Promise((resolve, reject) => { | |
setTimeout(() => reject(new Error('Rejected for some reason')), 1000); | |
}); | |
const somethingElse = () => Promise.reject({}); | |
// await something(); // top level await | |
const onRejected = () => console.log('Caught'); | |
const tryThis = async (asyncFunc) => { | |
try { | |
return await asyncFunc(); | |
} catch (error) { | |
console.log('Failed', error); | |
} | |
}; | |
const doSomething = async () => { | |
try { | |
const promise = something(); | |
console.log(promise); | |
// const result = await promise; | |
// console.log(result); | |
tryThis(() => somethingElse()); | |
console.log('continued'); | |
} catch (e) { | |
console.log('failed', e); | |
} | |
}; | |
doSomething(); | |
console.log('hello'); | |
const unhandledRejections = new Map(); | |
process.on('unhandledRejection', (reason, promise) => { | |
unhandledRejections.set(promise, reason.stack); | |
}); | |
process.on('exit', (code) => { | |
unhandledRejections.forEach((error) => console.log(error)); | |
process.exit(code); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
one-liner, if the return value is not needed:
const runAsync = (asyncFunction) => asyncFunction().catch(console.error);