Created
September 8, 2013 07:02
-
-
Save hitsthings/6482549 to your computer and use it in GitHub Desktop.
Node async compose. Reference for blog post at http://www.noiregrets.com/blog/2013/09/08/c2c15dbf/Functional-NodeJS-callback-composition
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
var toArray = Function.prototype.call.bind(Array.prototype.slice); | |
function partial(fn/*, ...args*/) { | |
var args = [].slice.call(arguments, 1); | |
return function() { | |
var lastArgs = toArray(arguments); | |
return fn.apply(this, args.concat(lastArgs)); | |
}; | |
} | |
function partialRight(fn/*, ...args*/) { | |
var args = [].slice.call(arguments, 1); | |
return function() { | |
var firstArgs = [].slice.call(arguments); | |
return fn.apply(this, | |
firstArgs.concat(args)); | |
}; | |
} | |
function handleError(errback, callback) { | |
return function(err) { | |
err ? | |
errback(err) : | |
callback.apply(this, | |
[].slice.call(arguments, 1)); | |
}; | |
} | |
function composeAsync() { | |
var fns = toArray(arguments); | |
return function() { | |
var args = toArray(arguments); | |
var next = args.pop(); | |
var nextOnError = partial(handleError, next); | |
var callFns = fns.map(nextOnError); | |
var call = callFns.reduce(function(next, fn) { | |
return partialRight(fn, next); | |
}, next); | |
call.apply(this, [ null ].concat(args)); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment