Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.