Skip to content

Instantly share code, notes, and snippets.

@coderek
Forked from tastywheat/taskQueue.js
Created July 25, 2014 02:02
Show Gist options
  • Save coderek/62b62b051fc9633e178c to your computer and use it in GitHub Desktop.
Save coderek/62b62b051fc9633e178c to your computer and use it in GitHub Desktop.
simple demonstration. this pattern is used by connect to stack middlewares
//process n number of async functions in order. used when promises aren't viable e.g. cross file or service calls.
var MiddlewareService = function(){
var stack = [],
isProcessingStack = false,
commonState = { task: 0 };
function push(fn){
stack.push(fn);
if(!isProcessingStack)
next();
}
function next(err){
if(err)
throw new Error(err);
var fn = stack.shift();
if(fn){
isProcessingStack = true;
fn(commonState, next);
}
else
isProcessingStack = false;
}
return {
push: push
};
}();
function doWork(commonState, next){
commonState.task++;
console.log('Starging something async:' + commonState.task);
setTimeout(function(){
console.log('Completed async task: ' + commonState.task);
next();
}, 2000);
}
MiddlewareService.push(doWork);
MiddlewareService.push(doWork);
MiddlewareService.push(doWork);
/* OUTPUT
Starging something async:1
Completed async task: 1
Starging something async:2
Completed async task: 2
Starging something async:3
Completed async task: 3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment