Last active
January 10, 2020 10:00
-
-
Save Gikkman/32d2312d92657b726288eeaeabcdffd0 to your computer and use it in GitHub Desktop.
Small convenience function for chaining functions that utilizes error-first callbacks
This file contains hidden or 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
| // ************************************************** | |
| // Lib code | |
| // ************************************************** | |
| function chainer(errHandler, functions) { | |
| // Copy functions array so rChainer doesn't modify the referenced array | |
| return (...input) => rChainer(errHandler, [...functions], ...input); | |
| } | |
| function rChainer(errHandler, functions, ...input) { | |
| let func = functions.shift();; | |
| if(func) func(...input, (err, ...val) => { | |
| if(err) return errHandler(err); | |
| else rChainer(errHandler, functions, ...val); | |
| }); | |
| } | |
| // ************************************************** | |
| // Example functions | |
| // ************************************************** | |
| function causesError() { | |
| return Math.random() > 0.9 ? true : false; | |
| } | |
| function first(a, callback) { | |
| if(causesError(a)) return callback("Error from first"); | |
| console.log(a); | |
| callback(null, a+1, a+2); | |
| }; | |
| function second(a, b, callback) { | |
| if(causesError(a) || causesError(b)) return callback("Error from second") | |
| console.log(a, b); | |
| callback(null, b+1, b+2, b+3); | |
| } | |
| function third(a, b, c, callback) { | |
| if(causesError(a) || causesError(b) || causesError(c)) return callback("Error from third") | |
| console.log(a, b, c); | |
| } | |
| // ************************************************** | |
| // Usage | |
| // ************************************************** | |
| let chain = chainer( | |
| err => console.log('Error:', err), | |
| [first, second, third] | |
| ); | |
| for(let i = 0; i < 20; i++) { | |
| chain(i); | |
| console.log('----------------------------------') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment