Skip to content

Instantly share code, notes, and snippets.

@javilobo8
Created November 11, 2019 14:13
Show Gist options
  • Save javilobo8/73c463854c9a8d69d8da94ae9a8db5eb to your computer and use it in GitHub Desktop.
Save javilobo8/73c463854c9a8d69d8da94ae9a8db5eb to your computer and use it in GitHub Desktop.
better promise
/* eslint-disable func-names, no-extend-native */
Promise.prototype.catch = function (...args) {
if (args.length === 0) {
throw new TypeError('0 arguments given');
}
if (typeof args[args.length - 1] !== 'function') {
throw new TypeError('Last argument must be a function');
}
if (args.length === 1) {
return this.then(undefined, err => args[0](err));
}
const errorClasses = args.splice(0, args.length - 2);
return this.then(undefined, (err) => {
for (let i = 0; i < errorClasses.length; i += 1) {
if (err instanceof errorClasses[i]) {
return args[args.length - 1](err);
}
}
return err;
});
};
Promise.prototype.tap = function (func) {
return this.then(func)
.then(() => this);
};
Promise.resolve(1)
.tap((d) => console.log('a', d))
.tap((d) => console.log('a', d))
.tap((d) => console.log('a', d))
.tap((d) => console.log('a', d))
.tap(async () => {
throw new Error('message');
})
.catch((err) => {
console.log('error', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment