Skip to content

Instantly share code, notes, and snippets.

@Gopikrishna19
Created April 25, 2021 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gopikrishna19/7946bcf8aa5b9507820294f5f208eceb to your computer and use it in GitHub Desktop.
Save Gopikrishna19/7946bcf8aa5b9507820294f5f208eceb to your computer and use it in GitHub Desktop.
try catch
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);
})
@vipranarayan14
Copy link

one-liner, if the return value is not needed:

const runAsync = (asyncFunction) => asyncFunction().catch(console.error);

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