Skip to content

Instantly share code, notes, and snippets.

@fernandocanizo
Last active December 2, 2016 20:02
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 fernandocanizo/f2accdca2dafa4b4ee50babed23078d8 to your computer and use it in GitHub Desktop.
Save fernandocanizo/f2accdca2dafa4b4ee50babed23078d8 to your computer and use it in GitHub Desktop.
Little snippet to show that you must catch anidated promises or return them to be catched by outer `catch()`
'use strict';
const willResolve = (value = true) => Promise.resolve(value);
const willReject = (msg = 'This is fucked up!') => Promise.reject(new Error(msg));
const toBeOrNotToBe = (value = true, msg = 'This may resolve... Or not') => {
(Math.random() > 0.5) ? Promise.resolve(value) : Promise.reject(msg);
};
// Anidated promise doesn't get catched by outer `catch()`. The next message will appear at the end:
// UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 4): Error: This is fucked up!
willResolve().then(() => {
willReject().then(() => console.log('reached reject'));
})
.catch((error) => console.log('Outter catcher:', error));
// An inner `catch()` is needed
willResolve().then(() => {
willReject(`Let's catch this one.`).then(() => console.log('reached reject'))
.catch((error) => console.log('Anidated catch:', error));
})
.catch((error) => console.log(error));
// Or better...
willResolve().then(() => {
return willReject('Catch this one too.').then(() => console.log(`This code won't run.`));
})
.catch((error) => console.log(`Now we're catching everything:`, error));
// in case you wanna play in the node console
module.exports = {
willResolve,
willReject,
toBeOrNotToBe,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment