Skip to content

Instantly share code, notes, and snippets.

@stringparser
Created April 1, 2015 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stringparser/05675a61a1f03f19ff4a to your computer and use it in GitHub Desktop.
Save stringparser/05675a61a1f03f19ff4a to your computer and use it in GitHub Desktop.
composing async functions
var store = {}; // lets say here we store things to map a string to a function
function Stack(){} // so we can identify composed functions
Stack.prototype.onHandle = function(next){
// measure times or other things
}
Stack.prototype.onHandleError = function(err){
if(err instanceof Error){ throw err; }
}
function compose(stack, site){
var stackArguments, end, result;
if(stack instanceof Stack){ tick(); }
else {
stackArguments = arguments;
tick.stack = new Stack();
return tick;
}
function next(err){
stack.onHandleError(err, next);
if(end){ return result; }
end = true;
stack.onHandle.apply(stack, args);
if(site.next){ compose(stack, site); }
return result;
}
function tick(err){
if(stackArguments){
stack = new Stack();
next.wait = stack.wait;
stack.onHandleError(err, next);
var host = arg instanceof Stack && arg
return compose(stack, {
args: util.slice(stackArguments, host ? -1 : 0),
index: -1,
host: host
});
}
var handle = site.next = site.args[++site.index];
var type = typeof handle;
if(type === 'string'){
handle = store[site.next];
}
if(type !== 'function'){
throw new TypeError('site should be string or function');
} else if(handle.stack instanceof Stack){
site.args[0] = stack;
} else {
site.args[0] = next;
}
var args = util.slice(site.args); // so we don't lose what was done before
util.asyncDone(function(){
stack.onHandle.apply(stack, args);
result = handle.apply(stack, args);
if(next.wait){ return result; }
if(site.next){ compose(stack, site); }
return result;
}, next);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment