Skip to content

Instantly share code, notes, and snippets.

@AkatQuas
Last active November 30, 2019 11:59
Show Gist options
  • Save AkatQuas/9bac72a5d133e707340312f9b1989d9a to your computer and use it in GitHub Desktop.
Save AkatQuas/9bac72a5d133e707340312f9b1989d9a to your computer and use it in GitHub Desktop.
Tricky code to intercept a promise. Awesome!
const NoopPromise = {
then: () => NoopPromise,
catch: () => NoopPromise,
};
Promise.resolve().then(() => {
const number = Math.random();
if (number > 0.5) {
return number;
}
// something bad happend,
// we have to stop the promise chain from here
// the rest chained code wouldn't execute,
// even with `catch` method
// ...
// do something error handler, like message, toast, event collection
// ...
return NoopPromise;
}).then((data) => {
console.log('We got the data from up-promise %d', data);
}).catch((e) => {
// This never printed
console.error('We encountered an error %o', e);
});
console.log('---');
Promise.resolve().then(() => {
throw new Error('Bad Promise');
}).catch((e) => {
console.error('We encountered an error %o', e);
return NoopPromise;
}).then(() => {
console.log('This never printed');
}).catch(() => {
console.log('This never printed');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment