Created
November 11, 2019 14:13
-
-
Save javilobo8/73c463854c9a8d69d8da94ae9a8db5eb to your computer and use it in GitHub Desktop.
better promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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