Skip to content

Instantly share code, notes, and snippets.

@rimiti

rimiti/index.js

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

This comment has been minimized.

Copy link
Owner Author

@rimiti 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
You can’t perform that action at this time.