Skip to content

Instantly share code, notes, and snippets.

@objectfoo
Last active September 16, 2018 18:31
Show Gist options
  • Select an option

  • Save objectfoo/0be15a27c237c2f8c0bf77446b85c1c7 to your computer and use it in GitHub Desktop.

Select an option

Save objectfoo/0be15a27c237c2f8c0bf77446b85c1c7 to your computer and use it in GitHub Desktop.
Explore when to throw vs reject
function asyncWork(options) {
let opt = options || {};
return new Promise((resolve, reject) => {
setTimeout(() => {
if (opt.error) {
const e = new Error(`An error has occured in "work ${opt.name}"`);
e.name = 'MyError';
// ERROR: throw is not caught by enclosing try catch
// throw e;
// Success: reject is caught by enclosing try catch
return reject(e);
}
resolve(opt.name);
}, opt.delay || 10);
});
}
async function main() {
// return Promise.reject(new Error('simulate unhandled promise rejection'));
try {
const result1 = await asyncWork({ name: 'one', delay: 1000 });
console.log(result1);
const result2 = await asyncWork({ name: 'two' });
console.log(result2);
// Success: this error is caught by try catch
// throw new Error('Success, error caught');
const result3 = await asyncWork({ name: 'three', error: true });
console.log(result3);
} catch(e) {
console.log(`Caught ${e.name}, message: ${e.message}`);
}
}
// hopefully this never gets invoked
process.on('uncaughtException', (e) => {
console.log('*** Error not caught');
});
// hopefully this never gets invoked
process.on('unhandledRejection', (e) => {
console.log('*** Promise rejection not caught');
});
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment