Skip to content

Instantly share code, notes, and snippets.

@Gopikrishna19

Gopikrishna19/try.js

Created Apr 25, 2021
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@vipranarayan14 vipranarayan14 commented Apr 25, 2021

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