Created
June 22, 2017 06:52
-
-
Save harish2704/90651dbe32b63fe6cdc1c62db14f2b89 to your computer and use it in GitHub Desktop.
catchIf syntax sugar for ES6 Promise. can be applied to any Promise library
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
/* | |
Adds a catchIf method to Promise. | |
Usage | |
Promise.reject( new TypeError() ) | |
.catchIf( TypeError, function handler(err){ console.log('TypeError handled')} ) | |
.catchIf( RangeError, function handler(err){ console.log('RangeError handled')} ) | |
*/ | |
function addCatchIf ( promiseClass ){ | |
promiseClass.prototype.catchIf = function(){ | |
const args = []; | |
let i = arguments.length; | |
if( i === 1 ){ | |
return this.catch( arguments[ 0 ] ); | |
} | |
while( i-- ){ | |
args[ i ] = arguments[ i ]; | |
} | |
const handler = args.pop(); | |
return this.catch(function(err){ | |
let i; | |
const l = args.length; | |
for ( i = 0; i < l; i++ ) { | |
if( err instanceof args[ i ] ){ | |
return handler( err ); | |
} | |
} | |
return promiseClass.reject(err); | |
}); | |
}; | |
} | |
addCatchIf( Promise ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment