Skip to content

Instantly share code, notes, and snippets.

@rimiti
Created April 5, 2018 10:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rimiti/697827faefe51022b561ab12e802a4ec to your computer and use it in GitHub Desktop.
Save rimiti/697827faefe51022b561ab12e802a4ec to your computer and use it in GitHub Desktop.
Node: Await without catching ? It's really bad...
const Test = (ms) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(ms === 20) reject(new Error('Bad value'));
resolve('ok');
}, ms);
});
}
async function testUnhandled() {
const res1 = await Test(10);
const res2 = await Test(20);
console.log('Test done.');
}
async function testHandledByTryCatch() {
try{
const res1 = await Test(10);
const res2 = await Test(20);
console.log('Test done.');
} catch (e) {
console.log('Error handled (global): ', e);
}
}
async function testHandledByCatch() {
const res1 = await Test(10).catch((e) => console.log('Error handled (res1): ', e));
const res2 = await Test(20).catch((e) => console.log('Error handled (res2): ', e));
console.log('Test done.');
}
testUnhandled();
testHandledByTryCatch();
testHandledByCatch();
@rimiti
Copy link
Author

rimiti commented Apr 5, 2018

Output:

$ node test.js
Error handled (res2):  Error: Bad value
    at Timeout.setTimeout [as _onTimeout] (/Users/dimitri/repositories/test.js:4:28)
    at ontimeout (timers.js:475:11)
    at tryOnTimeout (timers.js:310:5)
    at Timer.listOnTimeout (timers.js:270:5)
Error handled (global):  Error: Bad value
    at Timeout.setTimeout [as _onTimeout] (/Users/dimitri/repositories/test.js:4:28)
    at ontimeout (timers.js:475:11)
    at tryOnTimeout (timers.js:310:5)
    at Timer.listOnTimeout (timers.js:270:5)
Test done.
(node:54636) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Bad value
(node:54636) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

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